Python数组不工作

Python数组不工作,python,Python,这太简单了!为什么它不工作 我的python程序 def main(): mont = [] mont[0] = "bnkj1" mont[1] = "bnkj2" mont[2] = "bnkj3" print(mont[0]) main() 这是我运行它时得到的 Traceback (most recent call last): File "/Users/hunterjamesnelson/Documents/bruceArray.py",

这太简单了!为什么它不工作

我的python程序

def main():
    mont = []
    mont[0] = "bnkj1"
    mont[1] = "bnkj2"
    mont[2] = "bnkj3"

    print(mont[0])

main()
这是我运行它时得到的

Traceback (most recent call last):
  File "/Users/hunterjamesnelson/Documents/bruceArray.py", line 9, in <module>
    main()
  File "/Users/hunterjamesnelson/Documents/bruceArray.py", line 3, in main
    mont[0] = "bnkj1",
IndexError: list assignment index out of range
>>> 
回溯(最近一次呼叫最后一次):
文件“/Users/hunterjamesnelson/Documents/bruceArray.py”,第9行,在
main()
文件“/Users/hunterjamesnelson/Documents/bruceArray.py”,第3行,主目录
mont[0]=“bnkj1”,
索引器:列表分配索引超出范围
>>> 

谢谢

Python不允许仅通过分配给列表范围之外的索引来进行追加。您需要改用
.append

def main():
    mont = []
    mont.append("bnkj1")
    mont.append("bnkj2")
    mont.append("bnkj3")

    print(mont[0])

main()

问题是,在初始化列表时需要指定列表大小,以便像使用一样使用它。由于定义的列表长度为0,因此出现错误。因此,访问任何索引都将超出范围

def main():
    mont = [None]*3
    mont[0] = "bnkj1"
    mont[1] = "bnkj2"
    mont[2] = "bnkj3"

    print(mont[0])

main()
备选方案iv您可以使用
.append()
增加大小并添加元素。

def main():
def main():
    mont = []           # <- this is a zero-length list
    mont[0] = "bnkj1"   # <- there is no mont[0] to assign to

mont=[]#这避免了构建一个空列表,然后三次追加到它

def main():
    mont = ["bnkj1", "bnkj2", "bnkj3"]
    print(mont[0])

main()

或者在他的例子中只是
mont=['bnkj1','bnkj2','bnkj3']
;“数组”,对我们来说,意味着非常不同的东西,很少使用。