简体   繁体   中英

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)

However I want to remove all the occurrences of all the tuples in the format (1,x),So

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

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.

PS This function does not change your original list, it creates new one. 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.

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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