[英]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.