【问题标题】:Tried to implement List comprehension in Python 3.7x试图在 Python 3.7x 中实现列表理解
【发布时间】:2019-12-03 14:56:55
【问题描述】:

尝试通过以下示例在 Python 3.7x 中实现列表推导

a_list = [1, ‘4’, 9, ‘a’, 0, 4]
squared_ints = [ e**2 for e in a_list if type(e) == types.IntType ]  

但是它失败并出现以下错误

NameError: 名称“类型”未定义

谁能帮我解决这个问题?

【问题讨论】:

  • 为什么要定义types

标签: python-3.x list list-comprehension


【解决方案1】:

首先,NameError 是因为你需要先导入types 模块才能使用它:

import types 

但是,这仍然行不通,因为types.IntType 在 Python 3 中不存在; int 已经内置,所以没有必要。

最后,您通常不应该使用相等来进行类型比较;更喜欢isinstance 检查:

a_list = [1, '4', 9, 'a', 0, 4]
squared_ints = [ e**2 for e in a_list if isinstance(e, int)]  

【讨论】:

    【解决方案2】:

    既然它说,types 没有定义,你最好搜索你所引用的类。

    另一方面,另一种方法是:

    a_list = [1, ‘4’, 9, ‘a’, 0, 4]
    squared_ints = [ e**2 for e in a_list if type(e) == int ]  
    

    希望对你有帮助。

    【讨论】:

      【解决方案3】:

      你可以试试type(e) == int,而不是types.IntType

      squared_ints = [ e**2 for e in a_list if type(e) == int ] 
      

      对于内置数据类型,您可以按原样调用它们(即 int、str、dict、list、tuple、set 等)

      【讨论】:

        猜你喜欢
        • 2012-08-14
        • 2011-07-10
        • 1970-01-01
        • 1970-01-01
        • 2019-08-19
        • 1970-01-01
        • 1970-01-01
        • 2018-03-02
        • 2017-11-25
        相关资源
        最近更新 更多