如何以最有效的方式(最快的执行速度)编写“ for循环”?

时间:2019-01-22 14:30:28

标签: python list dictionary list-comprehension

我有以下代码:

all_sorted = [['9', 's'], ['11', 'h'], ['2', 's'], ['13', 'c'], ['13', 's'], ['11', 's'], ['3', 'd']]
pairness = {str(i): 0 for i in range(14, 1, -1)}
for card in all_sorted:
    pairness[card[0]] += 1

是否可以在效率更高的1行中编写第2-4行代码?

2 个答案:

答案 0 :(得分:3)

更短,但我不知道要快多少(可能根本不快)

>>> from collections import Counter
>>> Counter(x for x, _ in all_sorted)
Counter({'11': 2, '13': 2, '9': 1, '2': 1, '3': 1})

答案 1 :(得分:1)

使用collections.Counter的版本创建具有零值(与预期输出匹配)的密钥:

from collections import Counter

all_sorted = [['9', 's'], ['11', 'h'], ['2', 's'], ['13', 'c'], ['13', 's'], ['11', 's'], ['3', 'd']]
pairness = {**{str(i): 0 for i in range(14, 1, -1)}, **Counter(head for head, *_ in all_sorted)}

print(pairness)

输出

{'8': 0, '11': 2, '14': 0, '4': 0, '12': 0, '3': 1, '2': 1, '13': 2, '5': 0, '10': 0, '7': 0, '6': 0, '9': 1}