[英]How do i remove elements from a list without using remove(), or any other functions
假設,我有一個范圍從 1 到 50 的列表。我需要從列表中刪除所有具有因子f (用戶輸入)的整數(元素)。 例如,如果 = 2,則程序應從整數序列中刪除 4、6、8、10……,並打印序列中剩余的整數個數。 此練習中不允許使用諸如 remove() 之類的 Functions() 或任何其他函數。 我還在學習。
編輯:我不允許使用 enumerate()、切片、列表理解。 對不起。 如果有比我更好的方法來獲得 output,我願意接受。
lis = [1, 2, 3, 4, 5........51]
while True:
f = int(input())
if f == 0:
break
for i in lis:
if (i % f == 0 and i != f):
lis.remove(i)........#i cant figure how to remove without using remove()
c = len(lis)
print('Number of remaining integers:', c)
在不使用remove
的情況下,幾乎沒有辦法做到這一點。
第一個是創建一個新列表和append
到它所有要保存的數字並忽略其他數字:
lis = [1, 2, 3, 4, 5........50]
new_lis = []
while True:
f = int(input())
for num in lis:
if not (num % f == 0 and num != f):
new_lis.append(num)
lis = new_lis
c = len(lis)
print('Number of remaining integers:', c)
第二種解決方案是使列表中的數字無效,然后再次對其進行迭代並返回帶有list comprehension
的新數字:
lis = [1, 2, 3, 4, 5........50]
while True:
f = int(input())
for idx, num in enumerate(lis):
if (num % f == 0 and num != f):
lis[idx] = None
lis = [n for n in lis if n is not None]
c = len(lis)
print('Number of remaining integers:', c)
在這兩種解決方案中,我建議將lis
更改為l
,通常部分命名不會給出特殊值,因此不太推薦。
我會這樣做:
lis = [1, 2, 3, 4, 5........50]
while True:
f = int(input())
if f == 0:
break
new_lis = [item for item in lis if item == f or item % f != 0]
print('Number of remaining integers:', len(new_lis))
任何時候你有一個 for 循環將項目附加到列表中,並且列表開始為空 - 你很可能有一個列表理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.