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,910 points
2,194 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,300 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 28, 2019 in Python by Olly
3,099 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,020 points
2,683 views
+1 vote
1 answer
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
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,300 points
788 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,300 points
562 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP