You can accomplish this with list comprehension:
integers = [elm for elm in data if isinstance(elm, int)]
Where data
is the data. What the above does is create a new list, populate it with elements of data
(elm
) that meet the condition after the if
, which is checking if element is instance of an int
. You can also use filter
:
integers = list(filter(lambda elm: isinstance(elm, int), data))
The above will filter out elements based on the passed lambda, which filters out all non-integers. You can then apply it to the strings too, using isinstance(elm, str)
to check if instance of string.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…