简体   繁体   English

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

[英]How do I sort a zipped list in Python?

What's the Pythonic way to sort a zipped list?对压缩列表进行排序的 Pythonic 方式是什么?

code :代码 :

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

print zipped

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

I want to sort zipped by the values.我想作为排序依据的值压缩 So ideally it would end up looking like this [('x', 0), ('t', 1), ('a', 2), ('d', 3)] .所以理想情况下,它最终看起来像这样[('x', 0), ('t', 1), ('a', 2), ('d', 3)]

非常简单:

sorted(zipped, key=lambda x: x[1])
sorted(zipped, key = lambda t: t[1])
import operator
sorted(zipped, key=operator.itemgetter(1))

If you want it a little bit more faster, do ig = operator.itemgetter(1) and use ig as key function.如果您希望它更快一点,请执行ig = operator.itemgetter(1)并使用ig作为关键函数。

In your case you don't need to sort at all because you just want an enumerated reversed list of your names :在您的情况下,您根本不需要排序,因为您只需要一个枚举的倒序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')]

But if you need to sort it then you should use sorted (as provided by @utdemir or @Ulrich Dangel) because it will work on Python2 ( zip and itertools.zip ) and Python3 ( zip ) and won't fail with an AttributeError like .sort(...) (which only works on Python2 zip because there zip returns a list ):但是,如果您需要对其进行排序,那么您应该使用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'

But sorted does work in each case: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)]

It's simpler and more efficient to zip them in order in the first place (if you can).首先(如果可以)按顺序压缩它们更简单,更有效。 Given your example it's pretty easy:鉴于您的示例,这很容易:

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

Sort feature importance in a classifier (dtc=decision_tree):在分类器中对特征重要性进行排序 (dtc=decision_tree):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM