Filter list's elements by type of each element

后端 未结 2 1727
再見小時候
再見小時候 2020-12-19 10:13

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. H

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-19 10:41

    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']]
    

提交回复
热议问题