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

Sal*_*sov 2 python loops

在我写的下面的代码中,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
Run Code Online (Sandbox Code Playgroud)

我尝试使用嵌套for循环,

 for i in s:
     for j in range(0,5):
         if i == j:
             d["j"] += 1
Run Code Online (Sandbox Code Playgroud)

但我得到这个错误:

d["j"] += 1

KeyError: 'j'
Run Code Online (Sandbox Code Playgroud)

Mik*_*t25 7

您需要将整数转换为循环中的字符串.

for i in s:
    for j in range(0,5):
        if i == j:
            d[str(j)] += 1
Run Code Online (Sandbox Code Playgroud)


MSe*_*ert 7

您可以使用collections.Counter理解:

from collections import Counter

Counter(str(i) for i in s)
Run Code Online (Sandbox Code Playgroud)

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.
Run Code Online (Sandbox Code Playgroud)

或者如果你想把它作为普通字典,把它包装在一个dict调用中,例如:

dict(Counter(str(i) for i in s))
Run Code Online (Sandbox Code Playgroud)

KeyError当密钥不存在而你避免双循环时,两者都避免了.


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

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

然而Counter,defaultdict行为几乎像普通词典,所以几乎不需要最后一个,因为它(可能)较慢,在我看来不太可读.


SCB*_*SCB 6

除了Miket25的答案,您实际上可以使用数字作为字典键,例如:

d = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0 }

for i in s:
    # 0 <= i < 5 is the same as looking through and checking
    # all values 0-4 but more efficient and cleaner.
    if 0 <= i < 5:
        d[i] += 1
Run Code Online (Sandbox Code Playgroud)