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