我正在嘗試撰寫一些代碼,這部分不起作用。因為它一直說我的串列索引超出范圍,并且看起來我的串列中的專案正在消失。如果我看一下代碼,我找不到它為什么不起作用。有人知道為什么這不起作用嗎?
ts = [[4, 5], [9, 6], [2, 10]]
repeats = 3
for i in range(repeats):
cts = ts
t = ts[i]
cts.remove(t)
print(ts, t)
### [[6, 9], [2, 10]] [4, 5]
### [[6, 9]] [2, 10]
###
### Exception has occurred: IndexError
### list index out of range
###
### File "MyFile.py", line 12, in <module>
### t = ts[i]
uj5u.com熱心網友回復:
要從中洗掉值ts,您可以簡單地執行此操作。
ts = [[4, 5], [9, 6], [2, 10]]
for _ in range(len(ts)):
del ts[-1] # You can use `0` as well
或者
ts = [[4, 5], [9, 6], [2, 10]]
del ts
uj5u.com熱心網友回復:
為什么會發生這種情況是因為您cts = ts在每個回圈迭代中都有。因此,您正在修改原始ts串列。這段代碼應該做你需要的:
ts = [[4, 5], [9, 6], [2, 10]]
for i in range(len(ts)):
cts = ts.copy()
t = ts[i]
cts.remove(t)
print(ts, t)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/518384.html
標籤:Python列表
上一篇:有沒有更好的方法來查看一個字串是否包含在不同的字串串列中?
下一篇:使用輸入點獲取二維串列值(C#)
