[英]Counting elements which satisfy if statement and use this counter in list comprehension in Python?
例如,我們有任務,在列表中選擇前10個偶數。
這可以通過簡單的for循環輕松完成:
i = 0
list_even = []
for x in range(30):
if x % 2 == 0 and i < 10:
list_even.append(x)
i += 1
print(list_even) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] - correct!
怎么可能與列表理解相同?
我試圖使用枚舉,但它計算所有元素,不僅滿足if語句,所以我不能使用枚舉中的索引作為計數器。
list_even = [x for i, x in enumerate(range(30)) if x % 2 == 0 and i < 10]
print(list_even) # [0, 2, 4, 6, 8] - incorrect!
我描述的任務只是示例 - 我正在寫關於列表推導的文章,並希望了解這類任務的細節和一般解決方案。
首先只過濾,然后只計算已經過濾的值?
>>> [x for i, x in enumerate(x for x in range(30) if x % 2 == 0) if i < 10]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
雖然islice
可能是一個更好的方式來說你只想要前10個:
>>> list(itertools.islice((x for x in range(30) if x % 2 == 0), 10))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
如果時間/空間不是問題,或者只是獲取完整列表的一部分:
>>> [x for x in range(30) if x % 2 == 0][:10]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.