所以我想洗掉串列中數字的倍數(在本例中為 2)。由于某種原因,我的代碼基本上可以正常作業,數字 6 沒有被洗掉,知道如何解決這個問題嗎?
輸入:
def remove_multiples(l, n):
i = 0
while i < len(l):
element = l[i]
if element % n == 0:
l.remove(element)
i = 1
return l
l = [3,5,2,6,8,9]
print(remove_multiples(l, 2))
輸出:
[3, 5, 6, 9]
uj5u.com熱心網友回復:
我在 remove_multiples 函式中添加了一條列印陳述句,以查看回圈的行為方式。我認為了解您的方法后發生的事情可能很有用
def remove_multiples(lst, num):
i = 0
while i < len(lst):
# let's add a print to check how the loop is behaving
print(f"indexing elem {i}: value{l[i]}")
if l[i] % num == 0:
# we remove the item. even if we do not update i, due to the removal of the lst item, when the next iteration starts i will access the next element
l.pop(i)
else:
# we continue
i = 1
return lst
# or using list comphrension
def remove_multiples_v2(lst, num):
[i for i in lst if i % num != 0]
uj5u.com熱心網友回復:
嘗試這個:
def remove_multiples(lst, num):
return list(filter(lambda x: x % num, lst))
l = [3, 5, 2, 6, 8, 9]
print(remove_multiples(l, 2)) # [3, 5, 9]
uj5u.com熱心網友回復:
原因是串列的大小在迭代程序中會發生變化。從串列中洗掉 2(索引 2)后,您訪問索引 3,它不再是 6,而是 8
在這種情況下,最好迭代物件的副本。這樣,可以避免迭代期間的變化。
這應該作業
def remove_multiples(l, n):
for element in l[:]:
if element % n == 0:
l.remove(element)
return l
l = [3, 5, 2, 6, 8, 9]
print(remove_multiples(l, 2))
uj5u.com熱心網友回復:
每次從串列中洗掉元素時,串列的長度都會縮短。因此,您不會回圈瀏覽串列中的所有元素。換句話說,您的 while 回圈永遠不會達到 6。這就是它沒有被洗掉的原因。
嘗試這個:
def remove_multiples(l, n):
return [element for element in l if (element % n)]
l = [3, 5, 2, 6, 8, 9]
print(remove_multiples(l, 2))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515889.html
標籤:Python列表
