jeudi 7 janvier 2021

How to use index with the itertools function in Python

I have a list which contains multimple lists inside it and it looks like this:

import itertools

stand_city = 11
stand_liverpool = 6.5

premier_league = [
             ['A1','Manchester City', '10,1', 'Aguero'],
             ['A2','Manchester City', '11,2', 'Mahrez'],
             ['A3','Manchester City', '13,5', 'Sterling'],
             ['B1','Liverpool', '4,5', 'Mane'],
             ['B2','Liverpool', '5,6', 'Salah'],
             ['B3','Liverpool', '7,2', 'Jota']]

Now for every list I want to get the last value before it exceeds either stand_city or stand_liverpool. Depending on index[1] in the lists. If its Manchester City I need it to use stand_city, if Liverpool I want it to use stand_liverpool. I want those values to be stored in a new list.

This is my code:

new_list  = []
for key,sublists in itertools.groupby(premier_league,lambda y:y[0]):
    club = (list(sublists)[0][1])
    if club == 'Manchester City':
        v=[] 
        for v in itertools.takewhile(lambda x:float(x[-2].replace(",","."))<stand_city ,sublists):
            pass
        if v: 
            x = v[-1]
            new_list.append(x)
    elif club == 'Liverpool':
        v=[] 
        for v in itertools.takewhile(lambda x:float(x[-2].replace(",","."))<stand_liverpool ,sublists):
            pass
        if v: 
            x = v[-2]
            new_list.append(x)
            
print(new_list) 

This is my output:

[]

This is my desired output:

10,1
5,6

Aucun commentaire:

Enregistrer un commentaire