且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用嵌套的for循环替换重复的if语句?

更新时间:2022-05-17 08:55:34

您可以使用

You could use collections.Counter with a comprehension:

from collections import Counter

Counter(str(i) for i in s)

Counter在这里起作用,因为您要加一.但是,如果您希望它更通用,也可以使用 collections.defaultdict :

Counter works here because you're incrementing by one. However if you want it more general you could also use collections.defaultdict:

from collections import defaultdict

dd = defaultdict(int)   # use int as factory - this will generate 0s for missing entries
for i in s:
    dd[str(i)] += 1  # but you could also use += 2 or whatever here.

,或者如果您希望将其作为纯字典,则将其包装在dict调用中,例如:

or if you want it as plain dictionary, wrap it inside a dict call, for example:

dict(Counter(str(i) for i in s))

在键不存在时都避免使用KeyError,并且避免了双循环.

Both avoid KeyErrors when the key isn't present yet and you avoid the double loop.

作为旁注:如果您想要简单的命令,也可以使用 dict.get :

As a side note: If you want plain dicts you could also use dict.get:

d = {}  # empty dict
for i in d:
    d[str(i)] = d.get(str(i), 0) + 1

但是Counterdefaultdict的行为几乎像普通字典一样,因此几乎不需要最后一本字典,因为它(可能)比较慢,而且我认为可读性较低.

However Counter and defaultdict behave almost like plain dictionaries so there's almost no need for this last one, because it is (probably) slower and in my opinion less readable.