根据python中的每个其他元素对列表进行排序

时间:2014-11-08 16:53:46

标签: python list sorting structure python-3.4

如果我有一个包含结构的元素的列表:

[team1, points1, playedgames1, team2, points2, playedgames2, team3, points3, playedgames3]

等等。一个例子(有3个团队):

ls = ["Milan", 6, 2, "Inter", 3, 2, "Juventus", 5, 2]

并希望它看起来像这样:

["Inter", 3, 2, "Juventus", 5, 2, "Milan", 6, 2]

等等更多团队。如您所见,列表现在在最低点之后排序。基本上,它现在是:

["team2, points2, playedgames2, team3, points3, playedgames3, team1, points2, playedgames2]

由于points2具有最低值。那么,我可以对这些列表进行排序,关于这些点,还要保持列表的结构(团队,积分,玩游戏)等等。这可能吗?

从文本文件中检索元素。

4 个答案:

答案 0 :(得分:1)

我建议您将记录从文件转换为元组列表。 在它之后你可以通过简单的方式解决你的问题:

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
  sorted(a,key = operator.itemgetter(0))

     

10000个循环,最佳3:每循环114μs

     

在[18]中:%% timeit
  已排序(a,key = lambda x:x [0])

     

10000次循环,最佳3次:每次循环210μs

答案 1 :(得分:0)

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))

答案 2 :(得分:0)

这是一种方式:

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

答案 3 :(得分:0)

首先,您需要使用步骤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']