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

标签 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

这给了我以下错误:

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`

我相信这是因为 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)

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

编辑2:

for i in reversed(primeList):
        if i <= len(ls):
            del ls[i]
        else:
            continue
return ls

最佳答案

使用列表理解来避免就地改变列表:

return [v for i, v in enumerate(ls) if i not in primeList]

您正在从列表的前面一个一个地删除元素,因此其他元素每个都向上移动一个位置。第一次删除后,其余索引将相差一个,然后相差二,依此类推:

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

可以就地改变ls,但是您需要反向处理索引,以便您只删除尚未移动的索引:

for index_to_remove in reversed(primeList):
    del ls[index_to_remove]

但由于您已经制作了此处不需要的副本。

关于python - 从列表中删除元素,使用另一个列表作为索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28617058/

相关文章:

python - Scipy 的 fmin 有时只粘在 inf 上

python - 结合 GridSearchCV 和 StackingClassifier

python - django-cors-headers 不适用于 DRF(Django Rest Framework)

R中的递归for循环

ios - 快速无限循环的水平 UIScrollView

java - 编写一个方法,多次打印出字符串 "Name"

python unittest.TestCase.assertRaises 不工作

Python/Matplotlib - wxPython 中的图形边框

java - 我怎样才能只返回 String 方法的一部分?

python - 将数字分配给数据框中的行值