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

2024-05-10 01:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在我写的下面的代码中,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'

Tags: of代码innumberforifnprandom
3条回答

您需要在循环中将整数转换为字符串。你知道吗

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

除了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

你可以用^{}来理解:

from collections import Counter

Counter(str(i) for i in s)

Counter在这里工作,因为您的增量是1。但是,如果您希望它更通用,也可以使用^{}

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))

这两种方法都避免了键还没有出现时的KeyError,并且避免了双循环。你知道吗


另请注意:如果您想要普通的dict,也可以使用^{}

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

但是Counterdefaultdict的行为几乎像普通字典,所以几乎不需要最后一个,因为它(可能)比较慢,而且在我看来可读性较差。你知道吗

相关问题 更多 >