[英]print elements from a list until one element is found using list comprehension
so i was doing this exercise from w3schools所以我在 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.编写一个 Python 程序,以相同的顺序打印给定数字列表中的所有偶数,如果序列中 237 之后有任何数字,则停止打印。
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:使用 enumerate 和 % 运算符:
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: 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.用它的值替换end
以在一行中实现它。
Output: Output:
[12, 30, 10, 420]
[x for x in numbers[:numbers.index(237)] if x%2==0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.