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

后端 未结 4 1448
刺人心
刺人心 2020-12-14 14:39

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\',\         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-14 15:01

    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.

提交回复
热议问题