在python中排序两个列表?

Mal*_*lik 3 python sorting list

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

所以在分析结束时我有类似的东西

listWords : ["go", "make", "do", "some", "lot"]
listOccurrences: [2, 4, 8, 1, 5]
Run Code Online (Sandbox Code Playgroud)

我想在listOccurrences DESC之后对这两个列表进行排序,所以我会:

listWords : ["do", "lot", "make", "go", "some"]
listOccurrences: [8, 5, 4, 2, 1]
Run Code Online (Sandbox Code Playgroud)

有什么方法可以做到这一点吗?或者您是否知道任何其他方式比两个列表更"自然"?(就像单个"列表",其中每个出现都由一个单词引用)

bru*_*ers 8

>>> 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)
Run Code Online (Sandbox Code Playgroud)

请注意,键的明显数据类型:值对(此处:word:count)是a dict.FWIW你可能想看看collections.Counter.

编辑:为了完整起见:你也可以使用内置sorted()函数,而不是list.sort()如果你想在一行语句中填写所有这些(这可能不是一个好主意wrt/readability但这是另一个故事):

>>> listWords = ["go", "make", "do", "some", "lot"]
>>> listOccurrences = [2, 4, 8, 1, 5]
>>> listOccurrences, listWords = zip(*sorted(zip(listOccurrences, listWords), reverse=True))
>>> listWords
('do', 'lot', 'make', 'go', 'some')
>>> listOccurrences
(8, 5, 4, 2, 1)
Run Code Online (Sandbox Code Playgroud)