Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list's elements by type of each element

Tags:

python

I have list with different types of data (string, int, etc.). I need to create a new list with, for example, only int elements, and another list with only string elements. How to do it?

like image 847
Ilya Spark Avatar asked Oct 03 '16 04:10

Ilya Spark


People also ask

How do you filter data types in Python?

We can use the pandas. DataFrame. select_dtypes(include=None, exclude=None) method to select columns based on their data types. The method accepts either a list or a single data type in the parameters include and exclude.

How do you filter a list of strings?

Filter a list of string using filter() method. filter() method accepts two parameters. The first parameter takes a function name or None and the second parameter takes the name of the list variable as values. filter() method stores those data from the list if it returns true, otherwise, it discards the data.


2 Answers

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.

like image 173
Andrew Li Avatar answered Oct 12 '22 22:10

Andrew Li


Sort the list by type, and then use groupby to group it:

>>> import itertools
>>> l = ['a', 1, 2, 'b', 'e', 9.2, 'l']
>>> l.sort(key=lambda x: str(type(x)))
>>> lists = [list(v) for k,v in itertools.groupby(l, lambda x: str(type(x)))]
>>> lists
[[9.2], [1, 2], ['a', 'b', 'e', 'l']]
like image 31
TigerhawkT3 Avatar answered Oct 12 '22 23:10

TigerhawkT3