python和list / dict理解

时间:2016-02-08 17:13:15

标签: python python-2.7 dictionary list-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”方法?

2 个答案:

答案 0 :(得分:3)

很简单,因为虽然_dc_lc adict中的处理是空的,但在_forfor每次都会更新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

变为:

getPageWidth()

如果您需要跟踪一组密钥和出现次数,请使用collections.Counter(或for循环版本)。

答案 1 :(得分:1)

正如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