A shorter way to write python for a loop

Is there a shorter way to write this in Python? Here d is a python dictionary, a is a numpy array.

i = 0
for b in a:
    d[b] = a[:,i]
    i += 1

`

+4
source share
2 answers

A dict comp with enumerate :

d = {b: a[:,i] for i,b in enumerate(a)}

enumerategives you the index of each element in a, which is equivalent to your variable i. The first variable in the dict command is the key, the second is the equivalent value d[b] = a[:,i].

On the note side, if brepetition occurs, you will only get the last value for repetition b, since dicts cannot have duplicate keys.

+3

enumerate:

for i, b in enumerate(a):
    d[b] = a[:,i]

dict, :

d.update((b, a[:,i]) for i, b in enumerate(a))
+3

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


All Articles