[英]How do I assign a value inside list comprehension
我使用理解列表 python 編寫了一個小程序,我需要為字典分配一個值。
它給了我語法錯誤。
all_freq = {}
Input = 'google.com'
[all_freq[s] += 1 if s in Input else all_freq[s] = 1 for s in Input]
它說“[”沒有關閉。
請你幫助我好嗎。
使用普通for
循環,而不是列表推導,因為您沒有嘗試創建任何內容的列表。
all_freq = {}
for s in Input:
if s in all_freq:
all_freq[s] += 1
else:
all_freq[s] = 1
可以稍微簡化為
all_freq = {}
for s in Input:
if s not in all_freq:
all_freq[s] = 0
all_freq[s] += 1
可以完全替換為
from collections import Counter
all_freq = Counter(Input)
只是受到早期帖子的啟發,您也可以這樣做:
當然, Counter是做快速統計的最佳選擇。
from collections import defaultdict
all_freq = defaultdict(int) # initialize the dict to take 0, if key is not existing yet
for s in 'google': # each for-loop, just increment the *count* for corresponding letter
all_freq[s] += 1
print(all_freq)
defaultdict(<class 'int'>, {'g': 2, 'o': 2, 'l': 1, 'e': 1})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.