简体   繁体   中英

Using enumerate in a list expression gives unexpected result

I'm playing around with list expressions. This works:

>> l = [1, 4, 3, 4, 5]
>> z = [v for i, v in enumerate(l[0:-1]) if v < l[i + 1]]
>> print(z)
[1, 3, 4]

But this does not:

>> l = [1, 4, 3, 4, 5]
>> z = [v for i, v in enumerate(l[1:-1]) if v < l[i + 1]] # Changed from l[0:-1] -> l[1:-1]
>> print(z)
[] # It should print [3, 4]

They look almost identical -- what am I missing? Removing if v < l[i + 1] in the second expression returns the sublist l[1:-1] as expected.

enumerate() starts the count at 0 every time. You shortened l at the start by one element, but the i counter doesn't start at 1 , it still starts at 0 .

Pass in a start value as the second argument:

>>> [v for i, v in enumerate(l[1:-1], 1) if v < l[i + 1]]
[3, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM