Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 尝试在Python 3.7x中实现列表理解_Python 3.x_List_List Comprehension - Fatal编程技术网

Python 3.x 尝试在Python 3.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

尝试用以下示例在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) == 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)]  

为什么要定义
类型