TypeError:列表索引必须是整数或片,而不是元组,我很新,不明白为什么我的列表没有

2024-04-27 03:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

theListofSalary = [
["     $0 -   $9,999  ",": "]
["$10,000 -   $19,999 ",": "]
["$20,000 -   $29,999 ",": "]
["$30,000 -   $39,999 ",": "]
["$40,000 -   $49,999 ",": "]
["$50,000 -   $59,999 ",": "]
["$60,000 -   $69,999 ",": "]
["$70,000 -   $79,999 ",": "]
["$80,000 -   $89,999 ",": "]
["$90,000 -   $99,999 ",": "]
["$100,000 - $149,999 ",": "]
["$150,000 and over   ",": "]
]

正如标题所说,我不知道为什么列表列表会给我这个错误。我试图找出错误,但我是新来的,不能理解他们在说什么。你知道吗


Tags: and标题列表错误overthelistofsalary
3条回答

如其他答案所述,列表声明中的每个条目后面都缺少逗号(,)。然而,其他的答案并不能解释为什么你会看到这个奇怪的错误。你知道吗

现在的情况是,Python认为您正试图使用第二个内部列表索引到第一个内部列表,第二个内部列表恰好是一个元组数据类型(或逗号分隔的不可变列表)。你知道吗

print([""][0])    # this works and prints ""
print([""][0, 0]) # TypeError: list indices must be integers, not tuple

理解这一点很重要,因为以下代码不会给解释器带来任何问题,并且可能会在大型程序中导致非常微妙的错误:

theListofSalary = [
    ["     $0 -   $9,999  "]
    [0]
    [0]
    [0]
    [0]
    [0]
    [0]
    [0]
    [0]
    [0]
    [0]
    [0]
]
print(theListofSalary)

上面的代码打印[' ']。你知道为什么吗?你知道吗

另一个例子:

theListofSalary = [
    ["     $0 -   $9,999  "]
    [0]
    [12]
]
print(theListofSalary)

打印['$']。再说一次,你能理解为什么这样做吗?你知道吗

theListofSalary = [
    ["     $0 -   $9,999  "]
    [0]
    [80]
]
print(theListofSalary)

在上面的例子中,我们得到IndexError: string index out of range。你知道吗

theListofSalary = [
    ["     $0 -   $9,999  "]
    [0]
    ["hello world"]
]
print(theListofSalary)

上面的例子发出TypeError: string indices must be integers。你知道吗

希望你开始看到这里的模式!长话短说,确保在列表声明中添加逗号,这样解释器就不会将子列表误认为是第一个子列表上的索引操作。你知道吗

最后但同样重要的是,Python style guide表示snake_cased_variable_names。将列表命名为the_list_of_salaries是不必要的冗长;我建议简单地将此列表命名为salaries。你知道吗

在每个列表元素后面都缺少,

theListofSalary = [
    ["     $0 -   $9,999  ",": "], 
    ["$10,000 -   $19,999 ",": "],
    ....

主列表中的项目之间缺少逗号。你知道吗

theListofSalary = [
    ["     $0 -   $9,999  ",": "],
    ["$10,000 -   $19,999 ",": "],
    ["$20,000 -   $29,999 ",": "],
    ["$30,000 -   $39,999 ",": "],
    ["$40,000 -   $49,999 ",": "],
    ["$50,000 -   $59,999 ",": "],
    ["$60,000 -   $69,999 ",": "],
    ["$70,000 -   $79,999 ",": "],
    ["$80,000 -   $89,999 ",": "],
    ["$90,000 -   $99,999 ",": "],
    ["$100,000 - $149,999 ",": "],
    ["$150,000 and over   ",": "]
]

您会注意到,除了最后一个之外,我在所有文件中都添加了逗号,现在应该可以使用了:)

相关问题 更多 >