Python 3.x 尝试在Python 3.7x中实现列表理解
尝试用以下示例在Python3.7x中实现列表理解Python 3.x 尝试在Python 3.7x中实现列表理解,python-3.x,list,list-comprehension,Python 3.x,List,List Comprehension,尝试用以下示例在Python3.7x中实现列表理解 a_list = [1, ‘4’, 9, ‘a’, 0, 4] squared_ints = [ e**2 for e in a_list if type(e) == types.IntType ] 但是,它失败了,错误如下 NameError:未定义名称“类型” 有人能帮我吗?你可以试试type(e)=int,而不是types.IntType squared_ints = [ e**2 for e in a_list if type(e
a_list = [1, ‘4’, 9, ‘a’, 0, 4]
squared_ints = [ e**2 for e in a_list if type(e) == types.IntType ]
但是,它失败了,错误如下
NameError:未定义名称“类型”
有人能帮我吗?你可以试试
type(e)=int,而不是types.IntType
squared_ints = [ e**2 for e in a_list if type(e) == int ]
对于内置数据类型,您可以按原样调用它们(即int、str、dict、list、tuple、set等)因为它说,类型
没有定义,所以您最好搜索您引用的类
另一方面,另一种不同的方法是:
a_list = [1, ‘4’, 9, ‘a’, 0, 4]
squared_ints = [ e**2 for e in a_list if type(e) == int ]
希望有帮助。首先,名称错误是因为您需要先导入类型
模块,然后才能使用它:
import types
但是,这仍然不起作用,因为Python 3中不存在types.IntType
int
已作为内置组件提供,因此不需要
最后,您通常不应该使用相等进行类型比较;更喜欢支票:
a_list = [1, '4', 9, 'a', 0, 4]
squared_ints = [ e**2 for e in a_list if isinstance(e, int)]
为什么要定义类型
?