簡體   English   中英

在 python 的 for 循環中使用列表索引有什么意義?

[英]what is the significance of using list index in for loop of python?

我試圖理解以下代碼

a=[0,1,2,3]
for a[-1] in a:
    print(a[-1])

我期望一個無限循環打印 3 但 output 如下所示非常難以理解

output:

0
1
2
2

有人可以請解釋這段代碼的工作原理!

提前致謝

for循環中的in關鍵字與其他用例不同。

在此for循環列表中返回一個迭代器並將其分配給您的情況下的變量列表的最后一個元素

破壞你的代碼,這就是它在后台所做的事情

for i in a:
    a[-1] = i
    print(a[-1])

參考: https://docs.python.org/3/reference/compound_stmts.html#the-for-statement

Python 'in' 關鍵字在表達式與 for 循環中

暫無
暫無

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

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