so i was doing this exercise from w3schools
- Write a Python program to print all even numbers from a given numbers list in the same order and stop the printing if any numbers that come after 237 in the sequence.
and since i read about list comprehension i wanted to put it into practice, and i came to this
numbers = [ 233,12,59,213,69,923,30,10,420,237,432,
233,98,912,5,61]
print([x for i,x in enumerate(numbers) if i in
[i for i,x in enumerate(numbers[:numbers.index(237)])] and x % 2 == 0])
it works but is this the proper way of doing it? is it very ugly?
Use enumerate and the % operator:
numbers = [ 233,12,59,213,69,923,30,10,420,237,432,
233,98,912,5,61]
print([num for idx, num in enumerate(numbers) if num % 2 == 0 and idx < numbers.index(237)])
Output:
[12, 30, 10, 420]
end = numbers.index(237)
print([x for i,x in enumerate(numbers) if x%2==0 and i<end])
You could try this. Replace end
with it's value to implement it in a single line.
Output:
[12, 30, 10, 420]
[x for x in numbers[:numbers.index(237)] if x%2==0]
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.