簡體   English   中英

python和list / dict理解

[英]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是滿足您需求的最佳解決方案。

但是,如果您真的想保持列表/字典的理解力,我建議使用setcount

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM