Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

You can also do:

>>> OutputList = filter(ListTuples, lambda x: x[0] >= 50)
>>> OutputList
[(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.

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')]
>>>
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)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top