5 回答

TA貢獻1775條經驗 獲得超8個贊
您可以使用“del”關鍵字。即,del listA[i]
. 但是,您不應該這樣做,原因有兩個:
從列表中刪除隨機元素效率不高
在迭代列表時不應該改變列表。如果我在迭代列表時修改列表,會發生以下情況,請注意它沒有看到 2 個元素!
>>> a = [1, 2, 3, 4]
>>> for i, x in enumerate(a):
... print(x)
... del a[i]
...
1
3
最好創建一個臨時列表,例如 tmp_listA,附加到它,然后將其替換為原始列表。請勿修改原件。
看起來是這樣的:
listA = [1,3,10,12,50,52]
listB = []
tmpA = []
for i in range(len(listA)):
val = listA[i]
if val > 10:
listB.append(val)
else:
tmpA.append(val)
listA = tmpA
print(listA, listB)

TA貢獻1856條經驗 獲得超5個贊
給出替代方法:
listA = [1,3,10,12,50,52]
listB = [x for x in listA if not x>10]
listA = [x for x in listA if x>10]
print(listB)
# [1, 3, 10]
print(listA)
# [12, 50, 52]
```

TA貢獻1796條經驗 獲得超7個贊
我會使用簡單的列表理解。
listA = [1, 3, 10, 12, 50, 52]
listB = [item for item in listA if item > 10]
listA = [item for item in listA if item not in listB]
print(listA, listB)
#[1, 3, 10] [12, 50, 52]

TA貢獻1856條經驗 獲得超17個贊
這是一種更簡單、更易讀、直接的方法。
listA = [1,3,10,12,50,52]
listB = []
listA2 = []
for val in listA:
if val > 10:
listB.append(val)
else:
listA2.append(val)
listA = listA2
print(listA, listB)
輸出:
[1, 3, 10] [12, 50, 52]

TA貢獻1845條經驗 獲得超8個贊
您可以通過使用來做到這一點list.remove(value)
listA = [1,3,10,12,50,52,2,10,3,34]
listB = []
for i in range(len(listA)):
if listA[i] > 10:
listB.append(listA[i])
for val in listB:
listA.remove(val)
print(listA, listB)
添加回答
舉報