在我写的以下代码中,n = 4,所以有五个 if 语句,所以如果我想将 n 增加到,比如说 10,那么就会有很多 if。因此我的问题是:如何用更优雅的东西替换所有 if 语句?
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 循环,
for i in s:
for j in range(0,5):
if i == j:
d["j"] += 1
但是我得到这个错误:
d["j"] += 1
KeyError: 'j'
最佳答案
你可以使用 collections.Counter
理解:
from collections import Counter
Counter(str(i) for i in s)
Counter
在这里工作是因为你递增了一个。但是,如果您希望它更通用,您也可以使用 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
调用中,例如:
dict(Counter(str(i) for i in s))
两者都避免在 key 不存在时出现 KeyError
并且您避免了双循环。
作为旁注:如果你想要普通的字典,你也可以使用 dict.get
:
d = {} # empty dict
for i in d:
d[str(i)] = d.get(str(i), 0) + 1
但是 Counter
和 defaultdict
的行为几乎像普通字典,因此几乎不需要最后一个字典,因为它(可能)速度较慢并且在我看来可读性较差。
关于python - 用 python 中的嵌套 for 循环替换重复的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48015571/