根据python中的其他元素对列表进行排序
如果我有一个包含以下结构元素的列表:根据python中的其他元素对列表进行排序,python,list,sorting,structure,python-3.4,Python,List,Sorting,Structure,Python 3.4,如果我有一个包含以下结构元素的列表: [team1, points1, playedgames1, team2, points2, playedgames2, team3, points3, playedgames3] 等等。一个例子(有3个团队): 希望它看起来像这样: ["Inter", 3, 2, "Juventus", 5, 2, "Milan", 6, 2] 等等,为更多的团队。如您所见,列表现在排序在最低点之后。基本上,现在是: ["team2, points2, playedg
[team1, points1, playedgames1, team2, points2, playedgames2, team3, points3, playedgames3]
等等。一个例子(有3个团队):
希望它看起来像这样:
["Inter", 3, 2, "Juventus", 5, 2, "Milan", 6, 2]
等等,为更多的团队。如您所见,列表现在排序在最低点之后。基本上,现在是:
["team2, points2, playedgames2, team3, points3, playedgames3, team1, points2, playedgames2]
由于点S2的值最低。因此,我可以像这样对列表进行排序,根据积分,同时保留列表的结构(团队、积分、玩过的游戏)等等。这可能吗
元素从文本文件中检索。这里有一种方法:
import operator
L = (team1, points1, playedgames1, team2, points2, playedgames2, team3, points3, playedgames3)
L = [tuple(L[i:i+3]) for i in range(None, len(L), 3)]
answer = sorted(L, key=operator.itemgetter(2))
ls = ["Milan", 6, 2, "Inter", 3, 2, "Juventus", 5, 2]
>>> sorted([ls[i:i+3] for i in range(0,len(ls),3)], key=lambda x:x[1])
[['Inter', 3, 2], ['Juventus', 5, 2], ['Milan', 6, 2]]
我建议您将记录从文件转换为元组列表。 之后,您可以通过以下简单方法解决问题:
ls.sort(key=operator.itemgetter(0))
或者您可以创建函数:
def my_sort(my_list):
list_of_tuples = sorted([tuple(l[i:i+3]) for i in range(0, len(my_list), 3], key=operator.itemgetter(0))
arr = []
for i in b:
arr += [i[0]] + [i[1]]
return arr
另外,operator.itemgetter
工作得更快
在[17]中:%%timeit排序(a,key=operator.itemgetter(0)) 10000个回路,最好为3:114µs/回路 在[18]中:%%timeit
已排序(a,key=lambda x:x[0]) 10000个回路,最好为3个:每个回路210µs
首先,您需要使用步骤3拆分列表,然后根据第二个值的排序列表进行比较,然后根据第二个值的排序列表创建最后一个列表:
>>> new=[ls[i:i+3] for i in range(0,len(ls),3)]
>>> new
[('Milan', 6, 2), ('Inter', 3, 2), ('Juventus', 5, 2)]
>>> val2_l=sorted(zip(*new)[1])
>>> val2_l
[3, 5, 6]
>>> v=zip(*new)[1]
>>> v
(6, 3, 5)
>>> ["team{}, points{}, playedgames{}".format(v.index(i)+1,v.index(i)+1,v.index(i)+1) for i in val2_l]
['team2, points2, playedgames2', 'team3, points3, playedgames3', 'team1, points1, playedgames1']
>>> [''.join(last)]
['team2, points2, playedgames2team3, points3, playedgames3team1, points1, playedgames1']
如果它应该是一个列表(我不小心写了括号而不是括号,现在编辑了),那也行吗?谢谢!这正是我想要的,也是可以理解的!
>>> new=[ls[i:i+3] for i in range(0,len(ls),3)]
>>> new
[('Milan', 6, 2), ('Inter', 3, 2), ('Juventus', 5, 2)]
>>> val2_l=sorted(zip(*new)[1])
>>> val2_l
[3, 5, 6]
>>> v=zip(*new)[1]
>>> v
(6, 3, 5)
>>> ["team{}, points{}, playedgames{}".format(v.index(i)+1,v.index(i)+1,v.index(i)+1) for i in val2_l]
['team2, points2, playedgames2', 'team3, points3, playedgames3', 'team1, points1, playedgames1']
>>> [''.join(last)]
['team2, points2, playedgames2team3, points3, playedgames3team1, points1, playedgames1']