如何解决如何在 Python 中通过 itertools 函数使用索引
import itertools
stand_city = 11
stand_liverpool = 6.5
premier_league = [
['A1','Manchester City','10,1','Aguero'],['A2','11,2','Mahrez'],['A3','13,5','Sterling'],['B1','Liverpool','4,'Mane'],['B2','5,6','Salah'],['B3','7,'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
解决方法
我对您的代码做了一些小的修改以获得您想要的结果。
stand_city = 11
stand_liverpool = 6.5
premier_league = [
['A1','Manchester City','10,1','Aguero'],['A2','11,2','Mahrez'],['A3','13,5','Sterling'],['B1','Liverpool','4,'Mane'],['B2','5,6','Salah'],['B3','7,'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,6']
或者更短的方式
from itertools import groupby
res = []
for g,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,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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。