簡體   English   中英

通過“ for”循環(即“ for x in list:”)訪問列表時,有沒有辦法在同一循環中訪問列表中的“ x + 1”項目?

[英]While accessing a list through a “for” loop i.e. “for x in list:” , is there a way to access the “x+1” item in the list in the same loop?

通過for循環(即for x in list:x+1訪問for x in list: ,是否有辦法在同一循環中訪問列表中的x+1項?

例如,

list = [1 ,2 ,3 ,4]

有什么辦法可以添加1 + 2、2 + 3、3 + 4

for x in list:
    print(x+(x+1))

您可以按索引而不是值進行循環,並確保在倒數第二個索引處停止,以避免在訪問下一個索引時出現IndexError: list index out of range異常:

l = [1 ,2 ,3 ,4]

for i in range(len(l) - 1):
    print(l[i] + l[i + 1])

但是,更Pythonic的是使用自身的右移版本來zip列表:

l = [1 ,2 ,3 ,4]

for i, j in zip(l, l[1:]):
    print(i + j)

PS :避免將內置類型list用作變量名。

您有多個選擇。

一種是使用enumarate()

for counter, x in enumerate(a_list):
    print(str(x+a_list[counter+1]))

在最后一次迭代中將拋出IndexError,因此您也必須處理這種情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM