Python using enumerate inside list comprehension

后端 未结 7 2280
滥情空心
滥情空心 2020-11-28 01:49

Lets suppose I have a list like this:

mylist = [\"a\",\"b\",\"c\",\"d\"]

To get the values printed along with their index I can use Python\

7条回答
  •  离开以前
    2020-11-28 02:03

    Try this:

    [(i, j) for i, j in enumerate(mylist)]
    

    You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first:

    [pair for pair in enumerate(mylist)]
    

    Either way, the result that gets returned is as expected:

    > [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
    

提交回复
热议问题