简体   繁体   中英

Using OR in List Comprehension

For the life of me I can't figure out why this won't work. I'm trying to get the sum of a list however if the list contains the value 13 that value should be excluded form the sum and so should the following value. For example [1,13,3] would be 1 and [13,2,5] would be 5.

I have been trying this list comprehension:

lst = [3,3,13]
sum([lst[i] for i in range(len(lst)) if not lst[i] == 13 or not lst[i-1] == 13])

The OR seems to not be working like I expect. If I remove either part of the OR statement it works exactly as it should. Example

>>> lst = [3,3,13]
>>> [lst[i] for i in range(0,3) if not lst[i] == 13]
[3, 3]
>>> [lst[i] for i in range(len(lst)) if not lst[i] == 13 or not lst[i-1] == 13]
[3, 3, 13]

You have two errors in your code.

  1. If the last element is 13, then the first element with not be added because lst[0-1] == 13 because of Python's index wrap around.
  2. As stated in the comments and in the other answer, you should be using and , instead of or . This is because of De Morgan's laws .

Then, the resulting code is

sum([lst[i] for i in range(len(lst)) if not lst[i] == 13 and not(i > 0 and lst[i-1] == 13)])

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