简体   繁体   English

按每个元素的类型过滤列表的元素

[英]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.

相关问题 如何根据每个元素中的某些信息对列表的元素进行分组? - how to group element's of a list with respect of some information in each elements? 如何根据每个元素中的子字符串过滤列表? - How to filter a list based on a substring in each element? 列出100个元素,每个元素30个长 - List with 100 elements each element 30 long 将列表中每个元组的元素与列表中的每个元素相乘 - multiplication of elements of each tuple in a list with each element of a list 将每个列表的元素与列表中的其他元素进行比较 - Compare each list's element with others in the list 列出元素以考虑每个最近的 3 个邻居 - List elements to consider each's nearest 3 neighbors 将 dataframe 的每个列表类型元素更改为列表的第二个元素 - Changing each list type element of a dataframe to second element of the list 将列表中的每个元素与另一个列表中的 2 个元素进行比较并使代码高效 - comparing each element in list to 2 elements in another list and make code efficient 将一个列表的每个字符串元素连接到另一个列表的所有元素 - Concatenate each string element of one list to all elements of another list 检查一个列表的每个元素是否是另一个列表的所有元素的倍数 - Check if each element of one list is a multiple of all the elements of another list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM