[英]Python: iterating through a list and printing x elements at a time
假設我有一個列表:
n1 = [20, 21, 22, 23, 24]
我想遍歷列表並打印前三個元素,然后是序列的下三個元素,直到最后。 也就是說,我希望這是輸出:
20, 21, 22
21, 22, 23
22, 23, 24
我怎樣才能在 Python 中有效地做到這一點?
這是一個不太Python的解決方案,應該適合作為新程序員使用。 我們通過三元組中的最后一個數字來標識要打印的每個三元組數字,因此我們從索引22
,即2
,然后迭代到列表的末尾。
n1 = [20, 21, 22, 23, 24]
for i in range(2, len(n1)):
print(n1[i] + ',' + n1[i-1] + ',' + n2[i-2])
您可以嘗試以下方法:
n1 = [20, 21, 22, 23, 24]
listing = [', '.join(map(str, n1[i:i+3])) for i in range(len(n1)-2)]
for l in listing:
print(l)
輸出:
20, 21, 22
21, 22, 23
22, 23, 24
一種方法是對列表進行分塊並打印。 生成器功能有助於使此高效,明確和適應性強。 @Ned Batchelder提供 (在此處支持)。
def chunks(l, n):
"""Yield successive n-sized chunks from l."""
for i in range(0, len(l) - (n-1)):
yield l[i:i + n]
n1 = [20, 21, 22, 23, 24, 25]
for lst in chunks(n1, 3):
print(' '.join(map(str, lst)))
# 20 21 22
# 21 22 23
# 22 23 24
# 23 24 25
如果只想打印長度為3的塊,則可以在此處使用zip()
:
n1 = [20, 21, 22, 23, 24]
for x, y, z in zip(n1, n1[1:], n1[2:]):
print(x, y, z)
哪些輸出:
20 21 22
21 22 23
22 23 24
如果要打印出任何大小的塊,可以使用collections.deque
:
from collections import deque
from itertools import islice
def chunks(lst, n):
queue = deque(lst)
while len(queue) >= n:
yield list(islice(queue, 0, n))
queue.popleft()
n1 = [20, 21, 22, 23, 24]
for x in chunks(n1, 3):
print(*x)
# 20 21 22
# 21 22 23
# 22 23 24
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.