Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all strings from a list of tuples python

I am trying to remove all strings from a list of tuples

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

I have started to try and find a solution:

output = [i for i in ListTuples if i[0] == str]

print(output)

But I can't seem to get my head around how I would get an output like:

[(100), (80), (20), (40), (40)]

The format is always (int, str).

like image 423
a.rowland Avatar asked Jan 16 '19 14:01

a.rowland


People also ask

How do I remove a string from a tuple in Python?

When it is required to remove the strings froma tuple, the list comprehension and the 'type' method can be used. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

How do you delete all elements from a tuple in Python?

To explicitly remove an entire tuple, just use the del statement.

How do you remove a tuple from a list?

Use the del statement to remove a tuple from a list of tuples, e.g. del list_of_tuples[0] . The del statement can be used to remove a tuple from a list by its index, and can also be used to remove slices from a list of tuples.


3 Answers

Use a nested tuple comprehension and isinstance:

output = [tuple(j for j in i if not isinstance(j, str)) for i in ListTuples]

Output:

[(100,), (80,), (20,), (40,), (40,)]

Note that there are trailing commas in the tuples to distinguish them from e.g. (100) which is identical to 100.

like image 163
meowgoesthedog Avatar answered Nov 14 '22 21:11

meowgoesthedog


Since extracting the first item of each tuple is sufficient, you can unpack and use a list comprehension. For a list of tuples:

res = [(value,) for value, _ in ListTuples]  # [(100,), (80,), (20,), (40,), (40,)]

If you need just a list of integers:

res = [value for value, _ in ListTuples]     # [100, 80, 20, 40, 40]

For a functional alternative to the latter, you can use operator.itemgetter:

from operator import itemgetter
res = list(map(itemgetter(0), ListTuples))   # [100, 80, 20, 40, 40]
like image 32
jpp Avatar answered Nov 14 '22 23:11

jpp


Here's another solution using filter():

def non_string(x):
    return not isinstance(x, str)

print([tuple(filter(non_string, x)) for x in ListTuples])
# [(100,), (80,), (20,), (40,), (40,)]
like image 21
RoadRunner Avatar answered Nov 14 '22 21:11

RoadRunner