[英]python and list/dict comprehension
我正在學習一些列表/字典理解,並且被卡住了!!!
我真的不明白以下內容...
我有這個程序:
def histogram_for(word):
adict = dict()
for c in word:
adict[c] = adict.get(c, 0) + 1
print adict
return adict
def histogram_dc(word):
adict = dict()
adict = {c: (adict.get(c, 0) + 1) for c in word}
print adict
return adict
def histogram_lc(word):
adict = dict()
adict = dict([(c, (adict.get(c, 0) + 1)) for c in word])
print adict
return adict
word = "Football"
histogram_for(word.lower())
histogram_dc(word.lower())
histogram_lc(word.lower())
我得到這些結果:
{'a': 1, 'b': 1, 'f': 1, 'l': 2, 'o': 2, 't': 1}
{'a': 1, 'b': 1, 'f': 1, 'l': 1, 'o': 1, 't': 1}
{'a': 1, 'b': 1, 'f': 1, 'l': 1, 'o': 1, 't': 1}
為什么唯一可行的方法是“ for”方法?
很簡單,因為在_dc
進行處理時,而_lc
adict
為空,而在_for
則在for
循環的每一圈進行更新。 理解可以分解成自己的for
循環:
adict = dict()
adict = {c: (adict.get(c, 0) + 1) for c in word}
變為:
adict = dict()
# Handwaving for what Python actually does
$newdict = {}
for c in word:
$newdict[c] = adict.get(c, 0) + 1
adict = $newdict
如果您需要跟蹤一組鍵和出現次數,請使用collections.Counter
(或for循環版本)。
正如Sean Vieira所說,類collections.Counter
及其方法most_common
是滿足您需求的最佳解決方案。
但是,如果您真的想保持列表/字典的理解力,我建議使用set
和count
:
def histogram_dc(word):
adict = dict()
adict = {c: word.count(c) for c in set(word)}
print adict
return adict
def histogram_lc(word):
adict = dict()
adict = dict([(c, word.count(c)) for c in set(word)])
print adict
return adict
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.