从列表中删除元素,使用另一个列表作为索引

hja*_*mig 1 python loops

我有一个列表primeList和另一个列表ls.primeList是一个完整的列表,我需要删除ls索引所在的值primeList.

例如,如果primelist = [1, 3 , 5]ls = [1, 2, 3, 4, 5, 6, 7],则应删除索引1,3和5 ls,制作ls = [1, 3, 5, 7]

目前我正在尝试使用这段代码:

primeList = list(getPrimes())
    ls = list(ls)
    for i in primeList:
        del ls[i]
    return ls
Run Code Online (Sandbox Code Playgroud)

这给了我以下错误:

Traceback (most recent call last):
File "C:/Python34/My Scripts/NLP lab2/exec2.py", line 26, in <module>
otherList = delPrimes(myList)
File "C:/Python34/My Scripts/NLP lab2/exec2.py", line 18, in delPrimes
del ls[i]
IndexError: list assignment index out of range`
Run Code Online (Sandbox Code Playgroud)

我相信这是因为getPrimes是一个比ls更大的列表,但我不确定如何在Python中解决这个问题?

编辑 - 这是我目前的所有代码:

def delPrimes(*ls):

def getPrimes():
    L = []
    for x in range(2, 230):
        isPrime = True
        for y in range(2, x):
            if x % y == 0:
                isPrime = False
        if isPrime:
            L.append(x)
    return L

primeList = list(getPrimes())
ls = list(ls)
for i in primeList:
    del ls[i]
return ls

  myList = list(range(1, 51))

  print(myList)
  print("--" * 40)

  otherList = delPrimes(myList)

  print(otherList)
Run Code Online (Sandbox Code Playgroud)

作为一些功课的一部分,我们需要"在Python中编写一个方法来删除列表中主要索引位置的项目(直到索引位置50).例如,它将删除索引位置2,3,5,7处的项目, ......"我也相信我们必须使用'del'来删除.

EDIT2:

for i in reversed(primeList):
        if i <= len(ls):
            del ls[i]
        else:
            continue
return ls
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

使用列表推导来避免更改列表:

return [v for i, v in enumerate(ls) if i not in primeList]
Run Code Online (Sandbox Code Playgroud)

您将逐个删除列表前面的元素,因此其他元素每个都向上移动一个位置.在第一次删除之后,其余的索引然后是一个一个,然后是两个,等等:

>>> ls = [1, 2, 3, 4, 5, 6, 7]
>>> del ls[1]
>>> ls
[1, 3, 4, 5, 6, 7]
>>> ls[3]
5
>>> del ls[3]
>>> ls
[1, 3, 4, 6, 7]
>>> ls[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

可以ls在适当的位置进行更改,但是您需要反向处理索引,以便您只删除尚未移位的索引:

for index_to_remove in reversed(primeList):
    del ls[index_to_remove]
Run Code Online (Sandbox Code Playgroud)

但是因为你已经在这里制作了一份不必要的副本.