【问题标题】:'NoneType' object is not subscriptable in python'NoneType' 对象在 python 中不可下标
【发布时间】:2019-05-08 20:36:01
【问题描述】:
#i'm just testing it 

lst=[3, 2, 4, 5,1]

print([i for i in lst if i % 2 != 0].sort()[0])

#i haven't tried any thing        

#I expect the output 1

【问题讨论】:

  • #i haven't tried any thing -- 我建议您这样做:删除[0] 并查看表达式的类型(您可以使用type 或仅使用print)。

标签: sorting python-3.7 nonetype


【解决方案1】:

sort() 对列表进行就地排序并返回None。看起来您打算改用sorted

print(sorted([i for i in lst if i % 2 != 0])[0])

但是请注意,如果您只获取列表的第一个元素,则无需对列表进行排序。您可以使用min 来代替具有更好性能的相同结果(O(n) 而不是 O(nlog(n)):

print(min([i for i in lst if i % 2 != 0]))

【讨论】:

  • 或者使用 sorted like this heheheh
【解决方案2】:

sort() 正在修改方法并返回 None

这个有效:

lst=[3, 2, 4, 5,1]
odds = [i for i in lst if i % 2 != 0]
ods.sort()
print(ods[0])

【讨论】:

    【解决方案3】:

    这里的问题是,当您对列表运行“排序”函数时,此函数会更新列表并返回 void。因此,您确实是在尝试调用 NoneType 对象的索引。

    解决此问题的最佳方法是将过滤器设置为一个变量,对该变量运行排序,然后打印您想要的值。

    例如:

    l = [i for i in lst if i % 2 != 0]
    
    l.sort()
    
    print(l[0])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 2016-03-30
      • 2019-08-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多