我正在制作一個串列單詞計數器并嘗試合并兩個每個字符都有一個計數器的字典,但我一直得到錯誤的輸出。這是我試圖找出原因的嘗試。除了字典中的最后兩個鍵之外,一切似乎都很順利。
counts = {"a": 1, "p": 2, "l": 1, "e": 1}
new_counts = {"h": 1, "e": 1, "l": 2, "o": 1}
counts.update(new_counts)
for letters in counts:
if letters in counts and new_counts:
counts[letters] = 1
else:
counts[letters] = 1
print(counts)
我需要的:
{"a": 1, "p": 2, "l": 3, "e": 2, "h": 1, "o": 1}
我得到什么:
{'a': 2, 'p': 3, 'l': 3, 'e': 2, 'h': 2, 'o': 2}
uj5u.com熱心網友回復:
您可以使用一個簡單的 for 回圈:
counts = {"a": 1, "p": 2, "l": 1, "e": 1}
new_counts = {"h": 1, "e": 1, "l": 2, "o": 1}
for k, v in new_counts.items():
if k in counts:
counts[k] = v
else:
counts[k] = v
print(counts) # => {'a': 1, 'p': 2, 'l': 3, 'e': 2, 'h': 1, 'o': 1}
這實際上是最快的方法。我用timeitkosciej16的答案對其進行了測驗,他用了 5.49 秒,而我用了 0.73 秒(一百萬次迭代)。我還針對wim 的字典理解答案進行了測驗,這需要 1.95 秒,而我的需要 0.85 秒。
uj5u.com熱心網友回復:
如果我們在 Python 結構中,實際上它Counter在這里是理想的。
from collections import Counter
c1 = Counter({"a": 1, "p": 2, "l": 1, "e": 1})
c2 = Counter({"h": 1, "e": 1, "l": 2, "o": 1})
print(c1 c2)
uj5u.com熱心網友回復:
這將是一個理想的使用場所collections.defaultdict。創建一個新的defaultdict,我們遍歷兩個字典的專案并將它們的值添加到defaultdict.
>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> counts = {"a": 1, "p": 2, "l": 1, "e": 1}
>>> new_counts = {"h": 1, "e": 1, "l": 2, "o": 1}
>>> for k, v in counts.items():
... d[k] = v
...
>>> for k, v in new_counts.items():
... d[k] = v
...
>>> d
defaultdict(<class 'int'>, {'a': 1, 'p': 2, 'l': 3, 'e': 2, 'h': 1, 'o': 1})
uj5u.com熱心網友回復:
使用collections.Counter為這種事情設計的 dict 子類,您可以直接使用 運算子添加實體:
>>> from collections import Counter
>>> counts = {"a": 1, "p": 2, "l": 1, "e": 1}
>>> new_counts = {"h": 1, "e": 1, "l": 2, "o": 1}
>>> Counter(counts) Counter(new_counts)
Counter({'a': 1, 'p': 2, 'l': 3, 'e': 2, 'h': 1, 'o': 1})
使用 dict 理解:
>>> all_keys = counts.keys() | new_counts.keys()
>>> {k: counts.get(k, 0) new_counts.get(k, 0) for k in all_keys}
{'p': 2, 'h': 1, 'o': 1, 'e': 2, 'l': 3, 'a': 1}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/528182.html
標籤:Python字典柜台信
上一篇:如何列印出字典中的所有其他鍵?
