简体   繁体   English

Python,从列表中删除元素

[英]Python, removing elements from lists

Hi i'm a newbie and i have a problem with a function. 嗨,我是新手,我对功能有疑问。 I have two lists: 我有两个清单:

>>> a = ['a0', 'b1', 'a2', 'b3', 'a4', 'b5']
>>> b = ['b0', 'a1', 'b2', 'a3', 'b4', 'b5']

I want to remove elements in common and the bigger one in the same position; 我想删除相同位置上的相同元素和较大元素; my output should be: 我的输出应该是:

>>> function(a,b)
>>> a
['a0', 'a2', 'a4']
>>> b
['a1', 'a3']

I tried this: 我尝试了这个:

>>> def function(a,b):
        for i1,i2 in zip(a,b):
            if i1 == i2:
                a.remove(i1)
                b.remove(i2)
            elif i1 < i2:
                b.remove(i2)
            else:
                a.remove(i1) 

But it returns me: 但是它返回了我:

>>> function(a,b)
>>> a
['a0', 'b1', 'a2', 'b3', 'a4', 'b5']
>>> b
['a1', 'a3', 'b5']

What's my mistake? 我怎么了

In python 2 that would work but in python 3 zip has become a generator function: it creates the items on demand (more info here about various zip, izip stuff and differences between 2 & 3) 在python 2中可以工作,但是在python 3中, zip已成为生成器函数:它按需创建项目(有关各种zip,izip内容以及2和3之间差异的更多信息,请点击此处

Which means that since you're modifying a and b in the loop it amounts to iterating over changing lists (it's slightly less obivious because of the zip function). 这意味着,由于您要在循环中修改ab ,因此就意味着要遍历更改列表(由于zip函数的作用,它显得不太明显)。

To fix that, zip a copy of your input lists 要解决此问题,请压缩输入列表的副本

def function(a,b):
        for i1,i2 in zip(a[:],b[:]):
            if i1 == i2:
                a.remove(i1)
                b.remove(i2)
            elif i1 < i2:
                b.remove(i2)
            else:
                a.remove(i1) 

I have run your original code in my python 2.7 and it actually does output the values that you are looking for. 我已经在python 2.7中运行了原始代码,它实际上确实输出了您要查找的值。 But here is a more concise version for you to consider which also does the trick: 但是这里有一个更简洁的版本供您考虑,它也可以解决这个问题:

def function(a,b):
    for i1, i2 in zip(a,b):
        if i1 <= i2:
            b.remove(i2)
        if i2 <= i1:
            a.remove(i1)

a = ['a0', 'b1', 'a2', 'b3', 'a4', 'b5']
b = ['b0', 'a1', 'b2', 'a3', 'b4', 'b5']

function(a, b)


print a
>>>['a0', 'a2', 'a4']

print b
>>>['a1', 'a3']

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

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