Как использовать индекс с функцией itertools в Python

#python #list #if-statement #lambda #itertools

#python #Список #if-оператор #лямбда #itertools

Вопрос:

У меня есть список, который содержит несколько списков внутри него, и он выглядит так:

 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']]
 

Теперь для каждого списка я хочу получить последнее значение, прежде чем оно превысит либо stand_city или stand_liverpool . В зависимости от index[1] списков. Если Manchester City мне нужно, чтобы он использовался stand_city , если Liverpool я хочу, чтобы он использовался stand_liverpool . Я хочу, чтобы эти значения были сохранены в новом списке.

Это мой код:

 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) 
 

Это мой вывод:

 []
 

Это мой желаемый результат:

 10,1
5,6
 

Комментарии:

1. Почему вы используете y[0] in itertools.groupby(premier_league,lambda y:y[0]) , а не y[1] (название клуба)?

2. Почему 4,5 он включен в желаемый результат? Это не последнее значение, прежде чем значение для Liverpool превысит 6.5

3. mkrieger1 Верно, это ошибка. Я отредактировал желаемый результат.

Ответ №1:

Я внес некоторые небольшие изменения в ваш код, чтобы получить желаемый результат.

 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']]

res = []
for g, value in groupby(premier_league, key = lambda x:x[1]): # group by according to index 1
    less_than = [] # temporary list to hold all values less than your threshold for a particular group
    for i in value: # iterate thorugh the values in each group
        float_i = float(i[2].replace(',', '.')) # convert index 2 to float
        to_compare = stand_city if g == 'Manchester City' else stand_liverpool
        if float_i < to_compare: # compare `float_i` with either `stand_city` or `stand_liverpool` based on group
            less_than.append(i[2]) # add all values that meet the condition to a temp list
    res.extend(less_than[-1:]) # take only the last element from the list for each group, `[-1:]` is done to prevent cases where `less_than` is an empty list
print(res) # ['10,1', '5,6']
 

Или более коротким способом

 from itertools import groupby
res = []
for g, value in groupby(premier_league, key = lambda x:x[1]):
    last = [x[2] for x in value if float(x[2].replace(',', '.')) <= (stand_city if g == 'Manchester City' else stand_liverpool)][-1:]
    res.extend(last)

print(res) # ['10,1', '5,6']
 

Исправлен код OP для работы

 import itertools

new_list  = []
for key,sublists in itertools.groupby(premier_league,lambda y:y[1]):
    if key == 'Manchester City':
        v=[] 
        for v in itertools.takewhile(lambda x:float(x[-2].replace(",","."))<stand_city ,sublists):
            pass
        if v: 
            x = v[-2]
            new_list.append(x)
    elif key == '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)
 

Комментарии:

1. Можете ли вы объяснить, что вы сделали? Это выглядит хорошо и намного короче.

2. позвольте мне рассказать об этом

3. @TangerCity это подойдет?

4. Оке, спасибо, я проверю это. Ну, следующий вопрос: почему мой код не работает и что мне нужно для решения моего кода?

5. Ваши великие люди! Спасибо