我正在嘗試.remove()使用 for 回圈從串列中洗掉元素,但 for 回圈正在與不存在的值進行比較,并在它是最后一個元素時拋出錯誤。
這就是我想要做的:
print(positions)
for n in nk:
if n in nQ:
print(n)
positions.remove(n)
print(positions)
nk并nQ都列出了,我想洗掉的元素nk那是nQ。
當它不是串列中的最后一個元素時,它會回傳它,這是可以的:
[1, 5], [0, 5], [0, 4], [0, 3], [1, 3], [2, 3], [2, 4], [2, 5]]
[0, 3]
[[1, 5], [0, 5], [0, 4], [1, 3], [2, 3], [2, 4], [2, 5]]
[1, 3]
[[1, 5], [0, 5], [0, 4], [2, 3], [2, 4], [2, 5]]
[2, 3]
[[1, 5], [0, 5], [0, 4], [2, 4], [2, 5]]
但是當它是最后一個元素時會發生這種情況:
[[2, 7], [4, 7]]
[2, 7]
[[4, 7]]
[2, 6]
Traceback (most recent call last):
File "main.py", line 379, in <module>
print("Black King Moves:", findMovementsFork(board))
File "main.py", line 255, in findMovementsFork
positions.remove(n)
ValueError: list.remove(x): x not in list
來自哪里[2, 6],我該如何解決?
uj5u.com熱心網友回復:
迭代串列時不能洗掉元素。
您可以使用串列理解:
filtered_nk = [e for e in nk if e not in nQ]
uj5u.com熱心網友回復:
正確的方法是使用串列理解:
filtered_ls = [for n in nk if n not in nQ]
這實質上是構建一個新串列,包括該串列中不在 nQ 中的每個元素與原始串列的順序相同。
這樣做的原因是 Python 將嘗試遍歷您的整個串列,如果您在修改該串列的同時修改該串列,該串列將變得不穩定。考慮這個“展開”的例子:
ls = [1, 2, 3]
rem = [2]
# 'rolled' version
for x in ls:
if x in rem:
ls.remove(x)
# 'unrolled' version
idx = 0
x = ls[idx] # x = 1
in_rem = x in rem # in_rem == False
# skip removal
idx = idx 1
x = ls[idx] # x = 2
in_rem = x in rem # in_rem == False
ls.remove(x) # ls = [1, 3]
idx = idx 1
x = ls[idx] # Errors, because len(ls) == 2 now.
這大致相當于您正在嘗試的內容 - 略有不同,但上面應該表明,當您同時從串列中洗掉專案時,使用 for 回圈遍歷串列會導致問題。
串列理解的缺點是您基本上是在構建一個新串列,但就目前而言,它可能與您現在所做的一樣有效,除非沒有錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/313522.html
上一篇:for回圈在r中回圈通過向量
