简体   繁体   English

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

[英]Remove elements from a list, using another list as indices

I have a list primeList and another list ls . 我有一个列表primeList和另一个列表ls primeList is a list full of integers, and I need to delete the values from ls which have an index that is in primeList . primeList是一个充满整数的列表,我需要从ls删除具有在primeList的索引的值。

For example if primelist = [1, 3 , 5] and ls = [1, 2, 3, 4, 5, 6, 7] , then indexes 1, 3, and 5 should be removed from ls , making ls = [1, 3, 5, 7] 例如,如果primelist = [1, 3 , 5]ls = [1, 2, 3, 4, 5, 6, 7] ,则应从ls删除索引1、3和5,使ls = [1, 3, 5, 7]

At the moment I'm trying to use this bit of code: 目前,我正在尝试使用以下代码:

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

This gives me the following error: 这给了我以下错误:

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`

I believe this is because getPrimes is a larger list than ls, but I'm not sure how to work around this problem in Python? 我相信这是因为getPrimes的列表比ls大,但是我不确定如何在Python中解决此问题?

EDIT - This is all of my current code: 编辑-这是我当前的全部代码:

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)

As part of some schoolwork we need to "Write a method in Python to delete the items at prime index locations in a list (up to index location 50). Eg It will remove the item at index location 2, 3, 5, 7, … " I also believe we must use 'del' to do the deletion. 作为一些功课的一部分,我们需要“在Python中编写一种方法,以删除列表中主要索引位置(最高索引位置50)处的项目。例如,它将删除索引位置2、3、5、7, …“我也相信我们必须使用'del'进行删除。

EDIT2: 编辑2:

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

Use a list comprehension to avoid altering the list in place: 使用列表理解来避免更改列表:

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

You are deleting elements from the front of the list one by one, so the other elements each shift up one place. 您正在从列表的开头一开始删除元素,因此其他元素每个都向上移动一位。 After the first deletion the rest of your indices are then off-by-one, then off-by-two, etc: 第一次删除后,其余索引将一一分开,然后二一分开,依此类推:

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

You can alter ls in place, but then you need to handle the indices in reverse so that you are only deleting indices that haven't yet shifted: 可以就地更改ls ,但随后需要反向处理索引,以便仅删除尚未移动的索引:

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

but since you are already making a copy that's not necessary here. 但由于您已经在制作副本,因此在这里没有必要。

I see Martijn gave a complete answer before I did. 我看到Martijn在我之前给出了完整的答案。 His answer is correct, so I've upvoted him. 他的回答是正确的,所以我投票给他。 If there's something unclear ask away. 如果有不清楚的地方,请问。 A comment on your code. 对您的代码的注释。

Your code is poorly pasted or it's incorrect. 您的代码粘贴不良或不正确。 You have a return statement outside a function. 您在函数外部有一个return语句。 Apart from that I'm going to try and guess what you intention was since the code is mushed. 除此之外,我将尝试猜测由于代码被破坏而导致的意图。

If you use the * in you are doing something that's called unpacking values. 如果在其中使用* ,则表示执行的是拆包值。 I don't think that's necessary for what you need. 我认为这对于您所需要的不是必需的。

>>> def test(*ls):
        print ls
>>> test("a", "b", "c")
('a', 'b', 'c')
>>> ls = [1,2,3]
>>> test(ls)
([1, 2, 3],)

>>> def test(ls):
    print ls
>>> test("a", "b", "c")

Traceback (most recent call last):
  File "<pyshell#36>", line 1, in <module>
    test("a", "b", "c")
TypeError: test() takes exactly 1 argument (3 given)

I'm not so sure you really meant to do that. 我不确定您是否真的打算这样做。

You could rewrite your getPrimes function as well, so that you don't need to spend time on calculating all those primes (granted it's currently a small number, but since I'm already giving "tips" why not) 您也可以重写getPrimes函数,这样您就不需要花费时间来计算所有这些质数(当然,这是一个很小的数字,但是由于我已经给出了“技巧”,为什么不这样做)?

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

Now you can call that function like: 现在您可以像下面这样调用该函数:

>>> getPrimes(7)
[2, 3, 5, 7]

Which can come useful even when your list is not always the same because you can always call the function by just asking. 即使您的列表并不总是相同,这也很有用,因为您始终可以通过询问来调用函数。

>>> getPrimes(max(ls))
[2, 3, 5, 7]

Where max(ls) does the obvious and returns the largest element in the list (the highest prime you have). max(ls)在其中很明显,并返回列表中最大的元素(您拥有的最高质数)。 After that just follow Martijns instructions on how to delete the elements (reverse the order). 之后,只需遵循Martijns上有关如何删除元素的指示即可(颠倒顺序)。

And since Python is dynamically typed language, you don't need to explicitly convert the returns of your functions into types. 而且由于Python是动态类型化的语言,因此您无需将函数的返回值显式转换为类型。 So the list isn't really necessary in the lines primeList = list(getPrimes()) and ls = list(ls) unless ls is not a list from the start. 因此,除非ls从一开始就不是列表,否则在primeList = list(getPrimes())ls = list(ls)行中, list并不是必需的。 You most likely have that line because you have the unpacking operator * in your function which then returned ([1, 2, 3],) which is a type tuple (,) ("a pair of values") with a list [1,2,3] as first element. 您最可能有该行,因为您的函数中有拆包运算符* ,然后它返回([1, 2, 3],) ,它是带有列表[1,2,3] ([1, 2, 3],)的类型元组(,) (“一对值”)。 [1,2,3]作为第一个元素。

Hope I helped clear some things out. 希望我能帮忙解决一些问题。 Happy programing. 编程愉快。

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

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