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
).
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).
To explicitly remove an entire tuple, just use the del statement.
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.
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
.
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]
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,)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With