Replacing repeated if statements with nested loops in python?

In the following code I wrote, n = 4, and therefore there are five if statements, so if I would like to increase n to say, say 10, then there will be a lot of if. So my question is: how can I replace all if statements with something more elegant?

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

I tried using nested for loops,

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

But I get this error:

d["j"] += 1

KeyError: 'j'
+2
source share
4 answers

You can use collections.Counterwith understanding:

from collections import Counter

Counter(str(i) for i in s)

Counterworks here because you are incrementing by one. However, if you want it to be more general, you could also use 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))

KeyError, , .


: dicts, dict.get:

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

Counter defaultdict , , () , -, .

+7

.

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

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
+6

- :

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}
+1

Source: https://habr.com/ru/post/1691490/


All Articles