简体   繁体   English

如何使用 isinstance() 根据对象的类型将列表分成两个列表?

[英]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.groupbytype的通用解决方案。

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

as lists:作为列表:

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.

相关问题 根据元素的某些方面,如何将Python列表分成两个列表 - How to separate a Python list into two lists, according to some aspect of the elements 在两个单独的列表上使用相同的列表推导 - Using identical list comprehensions on two separate lists 如何根据条件将一个 python 列表分成 3 个不同的列表 - How to separate one python list into 3 different lists according to the criteria 如何将python列表上的每月和每天的文件名分成两个单独的列表? - How to separate monthly and daily filenames on python list into two separate lists? 如何根据每个子列表第一个条目中的值将 python 列表列表拆分为 3 个单独的列表? - How to split a python list of lists into 3 separate lists according to their value in the each sublist's first entry? 字符串化列表分为两个单独的列表 - stringified list to two separate lists 如何在不使用 NumPy 的情况下在单独的行中打印列表中的两个输入列表? - How to print two input lists within a list in separate lines without using NumPy? 如何将一个列表分为两个不同的列表?(Python2.7) - How to separate a list into two different lists ?(Python2.7) Python-如何将列表动态拆分为两个单独的列表 - Python - How to split a list into two separate lists dynamically 如何使用For循环在Python字典中的对象上应用isinstance() - How to apply isinstance() on objects in a Python dictionary using a For loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM