我有一个zip对象,我想对它进行排序(基于特定的键).
我已经看过如何在Python中对压缩列表进行排序?但是接受的答案在python 3.6中不起作用了.
例如
In [6]: a = [3,9,2,24,1,6]
In [7]: b = ['a','b','c','d','e']
In [8]: c = zip(a,b)
In [9]: c
Out[9]: <zip at 0x108f59ac8>
In [11]: type(c)
Out[11]: zip
In [12]: c.sort()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-a21727fa8976> in <module>()
----> 1 c.sort()
AttributeError: 'zip' object has no attribute 'sort'
# Wanted this to be sorted by the first element
In [13]: for l,r in c: print(l,r)
3 a
9 b
2 c
24 d
1 e
Run Code Online (Sandbox Code Playgroud)
换句话说,如何使zip迭代顺序符合排序顺序.我知道将zip转换为元组列表将允许我修复此问题,但我想保留压缩对象(因为它曾经是python2.7的旧时代)
Mar*_*ers 10
zip()在Python 3中返回一个迭代器 ; 当您从中请求元素时,输入会被压缩.迭代器不是可排序的,不是.
您可以使用该sorted()函数 "绘制"元素并从中返回排序列表:
sorted(zip(a, b))
Run Code Online (Sandbox Code Playgroud)
您还可以zip()通过调用对象将对象转换为列表list(),然后使用该list.sort()方法对该结果进行排序,但这比使用该sorted()函数更有用.
sorted()采用相同的关键字参数list.sort(),因此您仍然可以使用相同的key函数:
演示:
>>> a = [3, 9, 2, 24, 1, 6]
>>> b = ['a', 'b', 'c', 'd', 'e']
>>> sorted(zip(a, b))
[(1, 'e'), (2, 'c'), (3, 'a'), (9, 'b'), (24, 'd')]
>>> sorted(zip(a, b), key=lambda x: x[1])
[(3, 'a'), (9, 'b'), (2, 'c'), (24, 'd'), (1, 'e')]
Run Code Online (Sandbox Code Playgroud)
另请参阅`sorted(list)`vs`list.sort()`之间的区别是什么?蟒蛇
您不能sort在 zip 对象上使用,zip对象没有这样的属性。但是,您可以将zip对象转换为列表list(zipped_object),然后sort对其应用,以进行就地排序。
但是,由于压缩对象也是可迭代的,我的建议是使用sorted()。它还允许您编写一个排序函数,根据该函数对集合进行排序。
在这里,我根据y每(x,y)对中的值对其进行排序。。
>>> a = [3,9,2,24,1,6]
>>> b = ['a','b','c','d','e']
>>> c = zip(a,b)
>>>
>>> sorted(c, key = lambda x:x[1])
[(3, 'a'), (9, 'b'), (2, 'c'), (24, 'd'), (1, 'e')]
Run Code Online (Sandbox Code Playgroud)
请注意,sorted将返回一个新的排序列表,而sort将就地对集合进行排序。
| 归档时间: |
|
| 查看次数: |
13678 次 |
| 最近记录: |