Mustard Tiger
Mustard Tiger

Reputation: 3671

Python, remove all numbers from sublist

I have the following list: [['F', 'G', 'C'], ['S', 3, 7], ['C', 3, 'D']]

But I want to have: [['F', 'G', 'C'], ['S'], ['C', 'D']]

the elements in the list are all str objects. so basically this question is asking how can i get python to recognize a number even if it is cast as a string?

Upvotes: 1

Views: 134

Answers (1)

alecxe
alecxe

Reputation: 474231

You need a nested list comprehension and isinstance():

>>> l = [['F', 'G', 'C'], ['S', 3, 7], ['C', 3, 'D']]
>>> [[item for item in sublist if not isinstance(item, int)] for sublist in l]
[['F', 'G', 'C'], ['S'], ['C', 'D']]

If you need to handle digits inside strings also, str.isdigit() would help:

>>> l = [['F', 'G', 'C'], ['S', '3', '7'], ['C', '3', 'D']]
>>> [[item for item in sublist if not item.isdigit()] for sublist in l]
[['F', 'G', 'C'], ['S'], ['C', 'D']]

Upvotes: 3

Related Questions