Python “NoneType”对象不可下标?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18866657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:06:38  来源:igfitidea点击:

'NoneType' object is not subscriptable?

pythonpython-3.xnonetype

提问by user2786555

list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]
MASTERLIST = [list1, list2, list3]


def printer(list):
    print ("Available Lists:")
    listlen = (len(list))
    for x in range(listlen):
        print (list[x])[0]

This code is returning the "'NoneType' object is not subscriptable" error when I try and run printer(MASTERLIST). What did I do wrong?

当我尝试运行printer(MASTERLIST). 我做错了什么?

回答by Ethan Furman

The [0]needs to be inside the ).

[0]需求在里面的)

回答by TerryA

The print()function returns None. You are trying to index None. You can not, because 'NoneType' object is not subscriptable.

print()函数返回None。您正在尝试索引 None。你不能,因为'NoneType' object is not subscriptable.

Put the [0]inside the brackets. Now you're printing everything, and not just the first term.

[0]里面的括号。现在您正在打印所有内容,而不仅仅是第一项。

回答by Matthias

Don't use listas a variable name for it shadows the builtin.

不要list用作变量名,因为它会影响内置函数。

And there is no need to determine the length of the list. Just iterate over it.

并且不需要确定列表的长度。只需迭代它。

def printer(data):
    for element in data:
        print(element[0])

Just an addendum: Looking at the contents of the inner lists I think they might be the wrong data structure. It looks like you want to use a dictionary instead.

只是一个附录:查看内部列表的内容,我认为它们可能是错误的数据结构。看起来您想改用字典。

回答by Cam92

Point A: Don't use list as a variable name Point B: You don't need the [0] just

A 点:不要使用列表作为变量名 B 点:您不需要 [0] 只是

print(list[x])

回答by Reizz

The indexing e.g. [0] should occour inside of the print...

索引例如 [0] 应该出现在打​​印内部...

回答by Joshua Nixon

list1 = ["name1", "info1", 10]
list2 = ["name2", "info2", 30]
list3 = ["name3", "info3", 50]

def printer(*lists):
    for _list in lists:
        for ele in _list:
            print(ele, end = ", ")
        print()

printer(list1, list2, list3)