[英]Filter list's elements by type of each element
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. 我需要创建一个新列表,例如,只有int元素,另一个列表只有字符串元素。 How to do it? 怎么做?
You can accomplish this with list comprehension : 您可以使用列表理解来完成此任务:
integers = [elm for elm in data if isinstance(elm, int)]
Where data
is the data. 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
. 上面做的是创建一个新列表,用if
之后满足条件的data
元素( elm
)填充它,检查元素是否是int
实例。 You can also use filter
: 您还可以使用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. 以上将基于传递的lambda过滤掉元素,该lambda过滤掉所有非整数。 You can then apply it to the strings too, using isinstance(elm, str)
to check if instance of string. 然后,您可以使用isinstance(elm, str)
将其应用于字符串,以检查字符串的实例。
Sort the list by type, and then use groupby
to group it: 按类型对列表进行排序,然后使用groupby
进行分组:
>>> 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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.