简体   繁体   English

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

[英]How do i remove elements from a list without using remove(), or any other functions

Suppose, i have a list that has range from 1 to 50. I need to remove all the integers(elements) with factor f (user input) from the list.假设,我有一个范围从 1 到 50 的列表。我需要从列表中删除所有具有因子f (用户输入)的整数(元素)。 For example, if = 2, the program should remove 4, 6, 8, 10, … from the sequence of integers and print the remaining number of integers in the sequence.例如,如果 = 2,则程序应从整数序列中删除 4、6、8、10……,并打印序列中剩余的整数个数。 Functions() such as remove() or any other functions are not allowed for this exercise.此练习中不允许使用诸如 remove() 之类的 Functions() 或任何其他函数。 I'm still learning.我还在学习。

Edit: I'm not allowed to use enumerate(), slicing, list comprehension.编辑:我不允许使用 enumerate()、切片、列表理解。 Sorry.对不起。 If there's a better way of getting output than mine, I'm open to it.如果有比我更好的方法来获得 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)

There are few ways of doing that without using remove .在不使用remove的情况下,几乎没有办法做到这一点。

The first one is creating a new list and append to it all numbers which you want to save and ignore the other ones:第一个是创建一个新列表和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)

The second solution is to nullify the numbers in the list and then iterate on it again and return the new one with list comprehension :第二种解决方案是使列表中的数字无效,然后再次对其进行迭代并返回带有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)

In both solutions, i recommend change lis to be l , usually partial naming is not giving a special value and less recommended.在这两种解决方案中,我建议将lis更改为l ,通常部分命名不会给出特殊值,因此不太推荐。

This is how i would do it:我会这样做:

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))

Any time you have a for loop appending items to a list, and the list starts off empty - you might well have a list comprehension.任何时候你有一个 for 循环将项目附加到列表中,并且列表开始为空 - 你很可能有一个列表理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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