Python enumerate reverse index only

前端 未结 10 2231
情深已故
情深已故 2021-02-05 05:43

I am trying to reverse the index given by enumerate whilst retaining the original order of the list being enumerated.

Assume I have the following:



        
10条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 06:24

    Actually I'm using the same logic as @RemcoGerlich did, but I use list comprehension directly, which make the code now become 1-liner:

    def generatelist(x):
        return [(x-1-i,n) for i,n in enumerate(range(x))]
    

    Regarding the dilemma of choosing generator or list comprehension, here is the suggested way:

    Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.

提交回复
热议问题