Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting index of item while processing a list using map in python

Tags:

python

While processing a list using map(), I want to access index of the item while inside lambda. How can I do that?

For example

ranked_users = ['jon','bob','jane','alice','chris'] user_details = map(lambda x: {'name':x, 'rank':?}, ranked_users) 

How can I get rank of each user in above example?

like image 920
Jayesh Avatar asked Mar 25 '11 13:03

Jayesh


People also ask

How do you find the index of a list using an element?

To find the index of an element in a list, you use the index() function. It returns 3 as expected. However, if you attempt to find an element that doesn't exist in the list using the index() function, you'll get an error.

Can you index into a list Python?

Note. python lists are 0-indexed. So the first element is 0, second is 1, so on.


2 Answers

Use enumerate:

In [3]: user_details = [{'name':x, 'rank':i} for i,x in enumerate(ranked_users)]   In [4]: user_details Out[4]:  [{'name': 'jon', 'rank': 0},  {'name': 'bob', 'rank': 1},  {'name': 'jane', 'rank': 2},  {'name': 'alice', 'rank': 3},  {'name': 'chris', 'rank': 4}] 

PS. My first answer was

user_details = map(lambda (i,x): {'name':x, 'rank':i}, enumerate(ranked_users)) 

I'd strongly recommend using a list comprehension or generator expression over map and lambda whenever possible. List comprehensions are more readable, and tend to be faster to boot.

like image 64
unutbu Avatar answered Sep 29 '22 22:09

unutbu


Alternatively you could use a list comprehension rather than map() and lambda.

ranked_users = ['jon','bob','jane','alice','chris'] user_details = [{'name' : x, 'rank' : ranked_users.index(x)} for x in ranked_users] 

Output:

[{'name': 'jon', 'rank': 0}, {'name': 'bob', 'rank': 1}, {'name': 'jane', 'rank': 2}, {'name': 'alice', 'rank': 3}, {'name': 'chris', 'rank': 4}] 

List comprehensions are very powerful and are also faster than a combination of map and lambda.

like image 34
Prydie Avatar answered Sep 29 '22 20:09

Prydie