我想基于许多键对元组列表进行排序。例如,我有这个元组列表:
list_t = [(1, 3, 5, 6, 9, 10), (1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 2, 6, 7, 9, 54), (1, 3, 5, 6, 12, 43)]
有一次我想通过元组的第一,第二,第三和第五元素对它进行排序:
keys = [0, 1, 2, 4]
list_t_sorted = [(1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 2, 6, 7, 9, 54), (1, 3, 5, 6, 9, 10), (1, 3, 5, 6, 12, 43)]
另一次我需要通过元组的第三个元素对它进行排序:
keys = [2]
list_t_sorted = [(1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 3, 5, 6, 9, 10), (1, 3, 5, 6, 12, 43), (1, 2, 6, 7, 9, 54)]
到目前为止,我尝试了这段代码,但它没有返回预期的结果:
def sort_list(keys, list_t):
return sorted(list_t, key=lambda l: (l[x] for x in keys))
例如,对于keys = [0,1,2,4],它返回[(1,3,5,6,9,10),(1,2,3,4,5,61),(不是基于键排序的1,3,5,6,12,43),(1,2,6,7,9,54),(1,2,3,0,9,81)。
任何人都可以帮助我吗?谢谢!
答案 0 :(得分:6)
你走了。您可以详细了解operator.itemgetter
here in the docs。
import operator
list_t = [(1, 3, 5, 6, 9, 10), (1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 2, 6, 7, 9, 54), (1, 3, 5, 6, 12, 43)]
keys = [0, 1, 2, 4]
sorted(list_t, key=operator.itemgetter(*keys))
输出:
[(1, 2, 3, 4, 5, 61),
(1, 2, 3, 0, 9, 81),
(1, 2, 6, 7, 9, 54),
(1, 3, 5, 6, 9, 10),
(1, 3, 5, 6, 12, 43)]
答案 1 :(得分:2)
您正在尝试对生成器对象进行排序,我猜测它具有不同的等同方式。一种显示方法是通过显示实际尝试使用for循环排序的内容:
>>> def sort_list(keys, list_t):
... for l in list_t:
... print (l[x] for x in keys)
... return sorted(list_t, key = lambda l: (l[x] for x in keys))
...
>>> sort_list(keys, list_t)
<generator object <genexpr> at 0x105bc1af0>
<generator object <genexpr> at 0x105bc1af0>
<generator object <genexpr> at 0x105bc1af0>
<generator object <genexpr> at 0x105bc1af0>
<generator object <genexpr> at 0x105bc1af0>
[(1, 3, 5, 6, 12, 43), (1, 2, 6, 7, 9, 54), (1, 2, 3, 0, 9, 81), (1, 2, 3, 4, 5, 61), (1, 3, 5, 6, 9, 10)]
这显然不是您的预期输出,而是与这些发生器的比较方式有关。如果您想使用原始想法(没有itemgetter
),请明确创建tuples
而不是生成器:
>>> def sort_list(keys, list_t):
... return sorted(list_t, key = lambda l: tuple(l[x] for x in keys))
...
>>> sort_list(keys, list_t)
[(1, 2, 3, 4, 5, 61), (1, 2, 3, 0, 9, 81), (1, 2, 6, 7, 9, 54), (1, 3, 5, 6, 9, 10), (1, 3, 5, 6, 12, 43)]