Python排序不起作用

2024-05-15 08:25:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我有排序元组列表的代码:

s = "betty bought a bit of butter but the butter was bitter"
words = s.split()
l = []
k = []
unique_words = sorted(set(words))
for word in unique_words:
     k.append(word)
     l.append(words.count(word))

z = zip(k,l)
print z
reversed(sorted(z, key=lambda x: x[1]))
print z

z是一样的,列表不会被排序,甚至不会反转。在

我试图按count的整数值排序。在


Tags: 代码列表排序countbitword元组unique
3条回答

reversedsorted不进行适当的排序;而是返回新排序并反转的对象。将倒数第二行改为

z = list(reversed(sorted(z, key=lambda x: x[1])))

它会起作用的。list调用是因为reversed返回的是迭代器而不是列表(至少在Python3上)。在

执行以下操作可能不那么冗长

^{pr2}$

这几乎是正确的-如果您在Python REPL中检查help(reversed),您会发现它返回一个迭代器,其中包含基于dict值的排序结果。在

如果希望z在计数时存储更新的、反向排序的列表,则需要重新分配z:

z = list(reversed(sorted(z, key=lambda x: x[1])))

Edit:为了澄清一下,迭代器对象的最外层列表转换将迭代器“转换”为迭代器内部包含的对象列表。在

对于就地排序,应该使用z.sort()。在

如果坚持使用sorted,则将该值发送回z。在

所以,用其中一种

z.sort(key = lambda x:x[1])
z.reverse()

或者

^{pr2}$

或者,更复杂的解决方案可以是:

z = sorted(z, key=lambda x: x[1], reverse= True)

事实上,使用collections.Counter()可以更容易地得到最终结果

from collections import Counter 
z = sorted(Counter(s.split()).items(), key = lambda x:x[1], reverse = True)

按两个多个键进行排序是可以的,可以将它们作为元组传递。在您的情况下,解决方案是:

# first sort by negatives of the second item, then alphabetically. 
z = sorted(z, key=lambda x: (-x[1],x[0]))

输出:

[('butter', 2), ('a', 1), ('betty', 1), ('bit', 1), ('bitter', 1),
('bought', 1), ('but', 1), ('of', 1), ('the', 1), ('was', 1)]

相关问题 更多 >