[英]Subtract elements from one list from another list, using list comprehension. Returns incomplete list?
[英]print elements from a list until one element is found using list comprehension
所以我在 w3schools 做這個練習
- 編寫一個 Python 程序,以相同的順序打印給定數字列表中的所有偶數,如果序列中 237 之后有任何數字,則停止打印。
自從我讀到列表理解后,我想把它付諸實踐,我來到了這個
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])
它有效,但這是正確的做法嗎? 是不是很丑?
使用 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:
[12, 30, 10, 420]
end = numbers.index(237)
print([x for i,x in enumerate(numbers) if x%2==0 and i<end])
你可以試試這個。 用它的值替換end
以在一行中實現它。
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.