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

问题描述 投票:2回答:4

在我写的下面的代码中,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'
python loops
4个回答
7
投票

你可以使用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))

当密钥不存在时,两者都避免使用KeyErrors,并避免双循环。


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

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

然而Counterdefaultdict表现得几乎像普通词典,因此几乎不需要最后一个,因为它(可能)较慢,在我看来不太可读。


7
投票

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

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

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

1
投票

你可以尝试这样的东西,而无需导入任何外部模块:

在一行

import numpy as np
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 }


[d.__setitem__(str(i),d[str(i)]+1) for i in s  for j in range(0, 5) if str(i) in d]



print(d)

输出:(因为它是随机的,所以可以是任何东西)

{'1': 22, '3': 23, '0': 3, '4': 6, '2': 46}

详细解决方案

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

print(d)

输出:

{'4': 6, '0': 6, '3': 29, '1': 25, '2': 34}
© www.soinside.com 2019 - 2024. All rights reserved.