简体   繁体   中英

Remove tuple from list of tuples if certain condition is met

I have a list of tuples that look like this;

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]

I want to remove the tuples when the first element of the tuple is less than 50. The OutputList will look like this;

OutputList = [(100, 'AAA'), (80, 'BBB')]

How can this be done in python?

Thank you very much for your help.

You can easily do it as:

out_tup = [i for i in in_tup if i[0] >= 50]

[Out]: [(100, 'AAA'), (80, 'BBB')]

This simply creates a new list of tuples with only those tuples whose first element is greater than or equal to 50. Same result, however the approach is different. Instead of removing invalid tuples you accept the valid ones.

You can also do:

>>> OutputList = filter(ListTuples, lambda x: x[0] >= 50)
>>> OutputList
[(100, 'AAA'), (80, 'BBB')]

We can Do this with simple counter and a new list:

   new = []

   for i in ListTuples:
        for j in i:
            if ( counter % 2 == 0 ):
                if ( j > 50):
                    new.append(i)
            counter = counter +1

output :

[(100, 'AAA') , (80, 'BBB')]

Try this,

>>> ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
>>> new=[]
>>> for i in ListTuples:
    if i[0]>50:
        new.append(i)


>>> new
[(100, 'AAA'), (80, 'BBB')]
>>>

Code snippet for timing the solutions given by sshashank124 and Alex Thornton:

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
import timeit
timeit.timeit('[i for i in ListTuples if i[0] >= 50]', globals=globals(), number=1000000)
>>> 0.6041104920150246

timeit.timeit('filter(lambda x: x[0] >= 50, ListTuples)', globals=globals(), number=1000000)
>>> 0.3009479799948167

The build-in filter() solution is faster for this example.

ListTuples = [(100, 'AAA'), (80, 'BBB'), (20, 'CCC'), (40, 'DDD')]
out=[]
for item in ListTuples:
    if item[0]>50:
        out.append((item[0],item[1]))
print(out)

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