如何在Python中对压缩列表进行排序?

时间:2011-08-22 00:58:56

标签: python list sorting zip

排序压缩列表的Pythonic方法是什么?

代码:

names = list('datx')
vals  = reversed(list(xrange(len(names))))
zipped = zip(names, vals)

print zipped

上面的代码打印 [('d',3),('a',2),('t',1),('x',0)]

我想按值排序压缩。理想情况下,它最终看起来像 [('x',0),('t',1),('a',2),('d',3)]

6 个答案:

答案 0 :(得分:40)

非常简单:

sorted(zipped, key=lambda x: x[1])

答案 1 :(得分:27)

zipped.sort(key = lambda t: t[1])

答案 2 :(得分:8)

import operator
sorted(zipped, key=operator.itemgetter(1))

如果您想要更快一点,请ig = operator.itemgetter(1)并使用ig作为关键功能。

答案 3 :(得分:4)

首先按顺序拉链(如果可以的话)更简单,更有效。鉴于你的例子,这很容易:

>>> names = 'datx'
>>> zip(reversed(names), xrange(len(names)))
<<< [('x', 0), ('t', 1), ('a', 2), ('d', 3)]

答案 4 :(得分:3)

在您的情况下,您根本不需要排序,因为您只需要列出names的反向列表:

>>> list(enumerate(names[::-1]))      # reverse by slicing
[(0, 'x'), (1, 't'), (2, 'a'), (3, 'd')]

>>> list(enumerate(reversed(names)))  # but reversed is also possible
[(0, 'x'), (1, 't'), (2, 'a'), (3, 'd')]

但是如果你需要对它进行排序,那么你应该使用sorted(由@utdemir或@Ulrich Dangel提供),因为它可以在Python2(zipitertools.zip)上使用Python3(zip)并不会因AttributeError .sort(...)而失败(仅适用于Python2 zip,因为zip会返回list }):

>>> # Fails with Python 3's zip:
>>> zipped = zip(names, vals)
>>> zipped.sort(lambda x: x[1])
AttributeError: 'zip' object has no attribute 'sort'

>>> # Fails with Python 2's itertools izip:
>>> from itertools import izip
>>> zipped = izip(names, vals)
>>> zipped.sort(lambda x: x[1])
AttributeError: 'itertools.izip' object has no attribute 'sort'

但是sorted在每种情况下都有效:

>>> zipped = izip(names, vals)
>>> sorted(zipped, key=lambda x: x[1])
[('x', 0), ('t', 1), ('a', 2), ('d', 3)]

>>> zipped = zip(names, vals)  # python 3
>>> sorted(zipped, key=lambda x: x[1])
[('x', 0), ('t', 1), ('a', 2), ('d', 3)]

答案 5 :(得分:0)

在分类器(dtc = decision_tree)中对功能重要性进行排序:

for name, importance in sorted(zip(X_train.columns, 
                dtc.feature_importances_),key=lambda x: x[1]):
    print(name, importance)