简体   繁体   English

python和list / dict理解

[英]python and list/dict comprehension

I'm learning some list/dict comprehension and I'm stuck!!! 我正在学习一些列表/字典理解,并且被卡住了!!!

I really don't understand the following... 我真的不明白以下内容...

I have this program: 我有这个程序:

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())

And i get these results: 我得到这些结果:

{'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}

Why the only working one is the "for" method? 为什么唯一可行的方法是“ for”方法?

Quite simply because while the processing is happening in _dc and _lc adict is empty, while in _for it's being updated on each turn of the for loop. 很简单,因为在_dc进行处理时,而_lc adict为空,而在_for则在for循环的每一圈进行更新。 A comprehension can be de-sugared into a for loop of its own: 理解可以分解成自己的for循环:

adict = dict()
adict = {c: (adict.get(c, 0) + 1) for c in word}

becomes: 变为:

adict = dict()
# Handwaving for what Python actually does
$newdict = {}
for c in word:
    $newdict[c] = adict.get(c, 0) + 1
adict = $newdict

Use collections.Counter (or the for-loop version) if you need to keep track of a set of keys and counts of occurrences. 如果您需要跟踪一组键和出现次数,请使用collections.Counter (或for循环版本)。

As Sean Vieira said, the class collections.Counter and its method most_common are the best solution to your need. 正如Sean Vieira所说,类collections.Counter及其方法most_common是满足您需求的最佳解决方案。

But, if you really want to keep list/dict comprehension, I suggest using set and count : 但是,如果您真的想保持列表/字典的理解力,我建议使用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