Shorter way to write a Python for loop

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

i = 0
for b in a:
    d[b] = a[:,i]
    i += 1
Jan 17, 2019 in Python by ana1504.k
• 7,890 points
37 views

1 answer to this question.

0 votes
You can use the enumerate iterator:

for i, b in enumerate(a):
    d[b] = a[:,i]
And since you're going into a dict, you can do this:

d.update((b, a[:,i]) for i, b in enumerate(a))
answered Jan 17, 2019 by SDeb
• 13,230 points

Related Questions In Python

0 votes
1 answer
0 votes
1 answer

Is there a way to loop between 0 and 1 by 0.1 in python?

You can use the linespace function. It ...READ MORE

answered May 27, 2019 in Python by Olly
86 views
0 votes
1 answer

How to write a python script for downloading a video from YouTube and saving it to a directory?

First download pytube using the following code  pip ...READ MORE

answered Sep 4, 2019 in Python by Neel
• 3,010 points
488 views
+1 vote
1 answer
0 votes
1 answer
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 510 views
0 votes
0 answers
0 votes
1 answer

Best way to open a socket in Python

Opening sockets in python is pretty simple. ...READ MORE

answered Feb 21, 2019 in Python by SDeb
• 13,230 points
61 views
0 votes
1 answer

Find out time it took for a python script to complete execution

You can try the following code and ...READ MORE

answered Aug 6, 2019 in Python by SDeb
• 13,230 points
24 views