用python对两个列表排序?

2024-06-25 23:25:49 发布

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

我在计算文本中单词的出现次数,我有两个列表:第一个列表包含单词,第二个列表包含出现的单词。在

所以在分析的最后,我有一些

listWords : ["go", "make", "do", "some", "lot"]
listOccurrences: [2, 4, 8, 1, 5]

我想按照listcoccurrents DESC对这两个列表进行排序,因此我可以:

^{pr2}$

我有办法吗?或者你知道还有什么比两张单子更“自然”的吗?(就像一个单独的“列表”,每一次出现都被一个词引用)


Tags: 文本go列表make排序some单词次数
3条回答
>>> listWords = ["go", "make", "do", "some", "lot"]
>>> listOccurrences = [2, 4, 8, 1, 5]
>>> listTmp = zip(listOccurrences, listWords)
>>> listTmp
[(2, 'go'), (4, 'make'), (8, 'do'), (1, 'some'), (5, 'lot')]
>>> listTmp.sort(reverse=True)
>>> listTmp
[(8, 'do'), (5, 'lot'), (4, 'make'), (2, 'go'), (1, 'some')]
>>> zip(*listTmp)
[(8, 5, 4, 2, 1), ('do', 'lot', 'make', 'go', 'some')]
>>> listOccurrences, listWord = zip(*listTmp)

注意,对于键:值对(此处:单词:count)是一个dict。FWIW您可能想看看collections.Counter。在

编辑:为了完整起见:如果您想将所有这些都塞进一行语句中(这可能不是一个好主意,但这是另一个故事),那么您还可以使用内置的sorted()而不是{}函数:

^{pr2}$

另一种方法是在字典中保存数据。由于您正在计算单词的出现次数,因此listwords将具有唯一的单词,并且可以使用它作为字典键。可以使用python sorted方法按相同的顺序对键和值进行排序。在

listWords = ["go", "make", "do", "some", "lot"]

listOccurrences = [2, 4, 8, 1, 5]

dict = {}

i=0

while(len(listWords) > i):

    dict[listWords[i]] = listOccurrences[i];

    i = i + 1


print sorted(dict, key=dict.get, reverse=True)

print sorted(dict.values(), reverse=True)

我会用Counter。这是毫无意义的一句话:)

from collections import Counter

listWords, listOccurences = map(list, zip(*Counter(dict(zip(listWords, listOccurrences))).most_common()))

作为可读代码,您应该使用:

^{pr2}$

{提供给}返回到^列表的转换。在

另外,您可能希望首先使用Counter来收集频率数据(从here):

import collections

c = collections.Counter()
with open('/home/me/my_big_file_o_words') as f:
    for line in f:
        c.update(line.rstrip().lower())

print('Words ordered by most common:')
for letter, count in c.most_common():
    print(letter + ": " + count)

最后:在Python中,在变量名中使用下划线是一种时尚,而不是camelCase。也许改成list_words和{}?:)

相关问题 更多 >