Skip to main content
 首页 » 编程设计

python之如何仅从 Python 列表中获取不是字符串的元素

2025年05月04日21unruledboy

我试图只从列表中获取元素,而不是字符串。相反,它给出了一个空列表。这是为什么?

a = ['# this is a comment', 1, '# another comment', 2] 
data = [x for x in a if type(x) == 'str'] 
print(data) 

输出:[]

预期输出:[1, 2]

请您参考如下方法:

类型不是 'str'(参见 JavaScript 的 typeof 运算符,它确实返回字符串),它是 str.

a = ['# this is a comment', 1,'# another comment', 2] 
print([x for x in a if type(x) == 'str'])  # compares a type object to a string, no results 
print([x for x in a if type(x) == str])  # compares a type object to a type object, 2 results 

isinstance(x, str) 是检查类型的更好方法,因为它也处理子类。