简体   繁体   English

从列表中删除特定的元组

[英]Removing specific tuples from List

I've got a list 我有一个清单

a = [(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)]

If I say that: 如果我这样说:

for x in a:
    if x[0]==1:
        print x

I get the expected result : (1,2) (1,4) (1,8) (1,10) (1,6) 我得到了预期的结果:(1,2)(1,4)(1,8)(1,10)(1,6)

However I want to remove all the occurrences of all the tuples in the format (1,x),So 但是我想以(1,x)的格式删除所有元组的所有出现,所以

for x in a:
   if x[0]==1:
       a.remove(x)

I thought that all the occurences should be removed.However when i say 我认为应该删除所有出现的情况。

Print a

I get [(1,4),(2,6),(3,6),(1,6)] 我得到[(1,4),(2,6),(3,6),(1,6)]

Not all the tuples were removed. 并非所有元组都被删除。 How do I do it.?? 我该怎么做。?? Thanks 谢谢

I'd use list comprehension : 我会使用列表理解

def removeTuplesWithOne(lst):
    return [x for x in lst if x[0] != 1]

a = removeTuplesWithOne([(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)])

For me it's more pythonic than built-in filter function. 对我来说,它比内置filter功能更具有Python风格。

PS This function does not change your original list, it creates new one. PS此功能不会更改您的原始列表,而是会创建一个新列表。 If your original list is huge, i'd probably use generator expression like so: 如果您的原始列表很大,我可能会使用生成器表达式,如下所示:

def removeTuplesWithOne(lst):
    return (x for x in lst if x[0] != 1)

这与您的方法不同,但应该可以

a = filter(lambda x: x[0] != 1, a)

You can use list comprehension like this, to filter out the items which have 1 as the first element. 您可以像这样使用列表理解 ,以筛选出以1作为第一个元素的项目。

>>> original = [(1, 2), (1, 4), (2, 6), (1, 8), (3, 6), (1, 10), (1, 6)]
>>> [item for item in original if item[0] != 1]
[(2, 6), (3, 6)]

This creates a new list, rather than modifying the existing one. 这将创建一个新列表,而不是修改现有列表。 99% of the time, this will be fine, but if you need to modify the original list, you can do that by assigning back: 99%的时间都可以,但是如果您需要修改原始列表,则可以通过分配以下内容来实现:

original[:] = [item for item in original if item[0] != 1]

Here we use slice assignment, which works by replacing every item from the start to the end of the original list (the [:] ) with the items from the list comprehension. 在这里,我们使用切片分配,其工作原理是用列表推导中的项目替换原始列表( [:] )开头到结尾的每个项目。 If you just used normal assignment, you would just change what the name original pointed to, not actually modify the list itself. 如果您仅使用普通分配,则只需更改original名称所指向的名称,而不实际修改列表本身。

You can do it with a generator expression if you're dealing with huge amounts of data: 如果您要处理大量数据,则可以使用生成器表达式来实现:

a = [(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)]

# create a generator
a = ((x,y) for x, y in a if x == 1)

# simply convert it to a list if you need to...
>>> print list(a)
[(1, 2), (1, 4), (1, 8), (1, 10), (1, 6)]

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

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