Skip to main content
 首页 » 编程设计

python之在python 3中重复排序

2025年05月04日15findumars

我试图理解为什么不能多次在 python 3 中的 zip 对象上使用 sorted 函数。它只是第二次返回一个空列表。

In [34]: X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]  
    ...: Y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1] 
    ...: yx = zip(Y, X)  
    ...: yx  
    ...: [(0, 'a'), (1, 'b'), (1, 'c'), (0, 'd'), (1, 'e'), (2, 'f'), (2, 'g'),  
    ...: (0, 'h'), (1, 'i')]  
    ...: yx_sorted=sorted(yx) 
    ...:  
 
In [35]: yx_sorted 
Out[35]:  
[(0, 'a'), 
 (0, 'd'), 
 (0, 'h'), 
 (1, 'b'), 
 (1, 'c'), 
 (1, 'e'), 
 (1, 'i'), 
 (2, 'f'), 
 (2, 'g')] 
 
In [36]: yx_sorted=sorted(yx) 
 
In [37]: yx_sorted 
Out[37]: [] 
 
In [38]: yx 
Out[38]: <zip at 0x10476aa88> 

yx 在我看来仍然存在。

请您参考如下方法:

zip 是 Python 3 中的一个生成器。一旦你迭代了一次,它就用完了。