python - 通过字典中的不同值查找所有关键元素

标签 python python-2.7 list sorting dictionary

我有两个数组,我想使用两个数组创建一个字典,但我面临的问题是我希望重复值应该与列表中的重复值一样多。我正在使用这段代码

text_results = ['hello', 'foo' , 'hi' , 'good' , 'this' , 'hi' ]
scores = [4,2,4,5,1,4]
dictionary = dict(zip(scores,text_result)) 

我希望输出应该是这样的

[(4, 'hello'), (2, 'foo'), (4, 'hi') ,(5, 'good') ,(1, 'this'),(4, 'hi')]

我怎样才能像这样按降序排序:

[(5, 'good') ,(4, 'hello'),(4, 'hi'), (4, 'hi'), (2, 'foo') ,(1, 'this')]

最佳答案

排序元组

如果您想要一个已排序元组的列表,您可以使用 sorted 和相反的顺序对它们进行排序:

print(sorted(zip(scores, text_results), reverse=True))
# [(5, 'good'), (4, 'hi'), (4, 'hi'), (4, 'hello'), (2, 'foo'), (1, 'this')]

作为列表的值

如果您确实想要一个dict,您的值可以是列表。不过,Python 字典是无序的:

text_results = ['hello', 'foo' , 'hi' , 'good' , 'this' , 'hi' ]
scores = [4,2,4,5,1,4]

table = {}

for name, score in zip(text_results, scores):
    if not table.get(name):
        table[name] = []
    table[name].append(score)

print(table)
# {'this': [1], 'hi': [4, 4], 'foo': [2], 'hello': [4], 'good': [5]}

这样,如果您想要 hi 的值,您可以直接获取它们,而无需迭代列表:

>>> table.get('hello')
[4]
>>> table.get('hi')
[4, 4]
>>> table.get('not_here')
>>> 

请注意,此功能由 collections.defaultdict 提供。与defaultdict(list)。不过,我有时会发现额外的输出会分散注意力:

defaultdict(<type 'list'>, {'this': [1], 'hi': [4, 4], 'foo': [2], 'hello': [4], 'good': [5]})

关于python - 通过字典中的不同值查找所有关键元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44632301/

相关文章:

python - Tornado的 "yield"和asyncio的 "yield from"在机制上的区别?

Java - 列表中的所有元素变得相同

C++ 释放确切大小的内存

python - Matplotlib 实时 pyplot

python - Web 应用程序 : Hold large object between requests

python - 从 Pandas 中的 groupby .agg() 或 .apply() 有效地创建全新的数据框?

python - subprocess.call() 和 subprocess.Popen() 之间有什么区别使前者的 PIPE 安全性降低?

c# - UDP 将帧从 OpenCv 发送到 EmguCv

python - 路径名打开时间太长?

Python - "map"字典的键列表