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 in Python by ana1504.k
• 5,990 points
17 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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 by SDeb
• 9,540 points

Related Questions In Python

0 votes
1 answer
0 votes
1 answer

Best way to create a simple python web service

web.py is probably the simplest web framework ...READ MORE

answered Jul 20, 2018 in Python by Priyaj
• 56,120 points
18 views
0 votes
1 answer

What's the canonical way to check for type in Python?

To check if o is an instance ...READ MORE

answered Aug 24, 2018 in Python by Priyaj
• 56,120 points
14 views
0 votes
1 answer

Is there a foreach function in python and is there a way to implement it if there isnt any

Every occurence of "foreach" I've seen (PHP, ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,710 points
42 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
20 views
0 votes
1 answer

Best way to open a socket in Python

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

answered Feb 21 in Python by SDeb
• 9,540 points
37 views
0 votes
1 answer

Return a list inside a for loop while iterating over the elements of another list

The print() is getting called multiple times ...READ MORE

answered Sep 21, 2018 in Python by SDeb
• 9,540 points
22 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.