【问题标题】:Error: 'int' object is not subscriptable. ***python-jupyter_notebook [closed]错误:“int”对象不可下标。 ***python-jupyter_notebook [关闭]
【发布时间】:2021-06-02 10:29:16
【问题描述】:

我试图创建一个接受输入列表(混合类型)的函数,并且只从列表中提取数字。 我不断收到这个 'int' object is not subscriptable 错误。

List = ['M',1,'N',2,'0',3.5]
a_List = [x[:3] for x in List if type(x)!= str]
print(a_List)

【问题讨论】:

  • 您的列表中有整数,所以在某些时候x 是一个整数,那么在这种情况下x[:3] 是什么意思?
  • 3 个非字符串。我是编码新手。

标签: python list function for-loop


【解决方案1】:

此时,x 根据条件是一个整数,您不能制作整数切片。 试试x 而不是x[:3]

Listt = ['M',1,'N',2,'0',3.5]
a_List = [x for x in Listt if type(x)!= str]
print(a_List)
>> [1, 2, 3.5]

【讨论】:

    【解决方案2】:

    您可以使用列表推导。

    List = ['M',1,'N',2,'0',3.5]
    list_2 = [num for num in List if isinstance(num, (int,float))]
    

    【讨论】:

    • 感谢它现在工作正常。也是一种新的方式。
    • 很高兴它解决了您的问题!
    猜你喜欢
    • 2017-04-15
    • 2012-04-04
    • 2012-01-03
    • 2020-12-10
    • 2013-02-07
    • 2012-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多