Python 如何在不使用remove()或任何其他函数的情况下从列表中删除元素
假设我有一个从1到50的列表。我需要从列表中删除因子为f(用户输入)的所有整数(元素)。例如,如果没有使用Python 如何在不使用remove()或任何其他函数的情况下从列表中删除元素,python,python-3.x,list,Python,Python 3.x,List,假设我有一个从1到50的列表。我需要从列表中删除因子为f(用户输入)的所有整数(元素)。例如,如果没有使用remove的方法,则很少有这样做的方法 第一个是创建一个新列表,并在列表中附加所有要保存的数字,忽略其他数字: 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 !=
remove
的方法,则很少有这样做的方法
第一个是创建一个新列表,并在列表中附加所有要保存的数字,忽略其他数字:
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)
第二种解决方案是将列表中的数字置零,然后再次对其进行迭代,并使用列表理解返回新的数字
:
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]
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)
第二种解决方案是将列表中的数字置零,然后再次对其进行迭代,并使用列表理解返回新的数字
:
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循环将项目附加到列表中,并且列表开始时为空时,您都可能有一个列表理解。我会这样做:
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循环将项目附加到列表中,并且列表开始时为空时,您都可以理解列表。如果允许您创建一个对我来说最干净的新列表,请添加有效元素并跳过其他元素(使用列表)。请注意,在lis中使用
for i
迭代并删除元素通常是一个坏主意,因为循环将失败。如果允许您创建一个新列表,这对我来说是最干净的方式,请添加有效元素并跳过其他元素(使用列表)。请注意,在lis中使用for i进行迭代并删除元素通常是个坏主意,因为循环将失败。