问题描述
在我编写的以下代码中,n = 4,因此有五个if语句,因此,如果我想将n增加为10,那么将会有很多if.因此,我的问题是:如何用更优雅的东西替换所有的if语句?
In the following code that I wrote, n = 4, and so there are five if statements, so if I would like to increase n to be, say 10, then there will be a lot of if's. Therefore my question: how can I replace all the if statements with something more elegant?
n, p = 4, .5 # number of trials, probability of each trial
s = np.random.binomial(n, p, 100)
# result of flipping a coin 10 times, tested 1000 times.
d = {"0" : 0, "1" : 0, "2" : 0, "3" : 0, "4" : 0 }
for i in s:
if i == 0:
d["0"] += 1
if i == 1:
d["1"] += 1
if i == 2:
d["2"] += 1
if i == 3:
d["3"] += 1
if i == 4:
d["4"] += 1
我尝试使用嵌套的for循环
I tried using nested for loops,
for i in s:
for j in range(0,5):
if i == j:
d["j"] += 1
但是我得到这个错误:
d["j"] += 1
KeyError: 'j'
推荐答案
您可以使用 collections.Counter
理解为:
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 KeyError
s 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
但是Counter
和defaultdict
的行为几乎像普通字典一样,因此几乎不需要最后一本字典,因为它(可能)比较慢,而且我认为可读性较低.
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.
这篇关于用嵌套的for循环替换重复的if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!