[英]How to separate a list into two lists according to the objects' types using isinstance()?
With a list like this: ["apple", "orange", 5, "banana", 8, 9]
使用这样的列表:
["apple", "orange", 5, "banana", 8, 9]
How can I put the string(str) in one list and put integer(int) in another list using isinstance()?如何使用 isinstance() 将字符串 (str) 放入一个列表并将整数 (int) 放入另一个列表?
This way -这边走 -
a = ["apple", "orange", 5, "banana", 8, 9]
b1 = [el for el in a if isinstance(el, str)]
b2 = [el for el in a if isinstance(el, int)]
Use list comprehensions:使用列表理解:
lst = ["apple", "orange", 5, "banana", 8, 9]
strings = [s for s in lst if isinstance(s, str)]
integers = [n for n in lst if isinstance(n, int)]
Or, to avoid using two for
loops, you could also just loop over the list and append to the respective lists as needed:或者,为了避免使用两个
for
循环,您也可以根据需要循环遍历列表和 append 到相应的列表:
strings = list()
integers = list()
for l in lst:
if isinstance(l, str):
strings.append(l)
elif isinstance(l, int):
integers.append(l)
Here is a generic solution using itertools.groupby
and type
.这是使用
itertools.groupby
和type
的通用解决方案。
I chose here to return a dictionary as it is easy to get elements by name, but you could also return a list of lists.我在这里选择返回一个字典,因为它很容易通过名称获取元素,但您也可以返回一个列表列表。
from itertools import groupby
l = ["apple", "orange", 5, "banana", 8, 9]
grouper = lambda x: type(x).__name__
{k:list(g) for k,g in groupby(sorted(l, key=grouper), grouper)}
output: output:
{'int': [5, 8, 9], 'str': ['apple', 'orange', 'banana']}
ints, strings = [list(g) for k,g in groupby(sorted(l, key=grouper), grouper)]
output: output:
>>> ints
[5, 8, 9]
>>> strings
['apple', 'orange', 'banana']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.