簡體   English   中英

如何使用 isinstance() 根據對象的類型將列表分成兩個列表?

[英]How to separate a list into two lists according to the objects' types using isinstance()?

使用這樣的列表: ["apple", "orange", 5, "banana", 8, 9]

如何使用 isinstance() 將字符串 (str) 放入一個列表並將整數 (int) 放入另一個列表?

這邊走 -

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

使用列表理解:

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

或者,為了避免使用兩個for循環,您也可以根據需要循環遍歷列表和 append 到相應的列表:

strings = list()
integers = list()

for l in lst:
    if isinstance(l, str):
        strings.append(l)
    elif isinstance(l, int):
        integers.append(l)

這是使用itertools.groupbytype的通用解決方案。

我在這里選擇返回一個字典,因為它很容易通過名稱獲取元素,但您也可以返回一個列表列表。

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:

{'int': [5, 8, 9], 'str': ['apple', 'orange', 'banana']}

作為列表:

ints, strings = [list(g) for k,g in groupby(sorted(l, key=grouper), grouper)]

output:

>>> ints
[5, 8, 9]
>>> strings
['apple', 'orange', 'banana']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM