gpt4 book ai didi

python - 在Python中使用for循环在嵌套列表中赋值

转载 作者:太空宇宙 更新时间:2023-11-03 19:28:53 26 4
gpt4 key购买 nike

我需要创建一个四层深度的嵌套列表。第四个层面,我需要系统地赋值。当第四级处于第一个循环的中间时,无论分配的值如何,我都会收到索引错误,如您在代码下方的输出中看到的那样。

    fourNest = [ [[[[[AA, BB, CC, DD]
for AA in range(2)]
for BB in range(3)]
for CC in range(4)]
for DD in range(5)]]

print fourNest #this prints as expected and assignments work manually


for AA in range(2):
print "AA = ", AA
for BB in range(3):
print " BB = ", BB
for CC in range(4):
print " CC = ", CC
for DD in range(5):


fourNest[AA][BB][CC][DD] = 1

print " DD = ", DD," ", fourNest[AA][BB][CC][DD]
AA =  0BB =  0CC =  0DD =  0           1DD =  1           1DD =  2           1
Traceback (most recent call last):
File "C:/Python27/forListCreateTest", line 21, in <module>
fourNest[AA][BB][CC][DD] = 1
IndexError: list assignment index out of range

最佳答案

LC 中的循环顺序需要颠倒。您还有一层额外的括号

fourNest = [[[[[AA, BB, CC, DD]
for DD in range(5)]
for CC in range(4)]
for BB in range(3)]
for AA in range(2)]

关于python - 在Python中使用for循环在嵌套列表中赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7003821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com