<p>在我写的下面的代码中,n=4,所以有五个if语句,如果我想把n增加到10,那么会有很多if语句。因此我的问题是:如何用更优雅的语句替换所有if语句?你知道吗</p>
<pre><code>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
</code></pre>
<p>我试着用嵌套for循环</p>
<pre><code> for i in s:
for j in range(0,5):
if i == j:
d["j"] += 1
</code></pre>
<p>但我有个错误:</p>
<pre><code>d["j"] += 1
KeyError: 'j'
</code></pre>