繁体   English   中英

如何在不使用 remove() 或任何其他函数的情况下从列表中删除元素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM