使用for循环引用变量

2024-10-05 10:22:44 发布

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

我对python还比较陌生,不知道是否有人能帮我解决以下问题:

在收到用户关于圣诞树的高度和基本树枝长度的输入后,我正在尝试映射圣诞树。以下是我目前拥有的代码:

tree_map_5 = ['B']
tree_map_4 = ['B']
tree_map_3 = ['B']
tree_map_2 = ['B']
tree_map_1 = ['B']
# (B means Bark (For the trunk))

Layers = int(input("\nHow many layers will your christmas tree have? (Maximum 5)\n\nInput: "))
Base_Branch_Length = int(input("\nHow long will the base branches of your tree be? (in centimetres)\n\nInput: "))

for i in range (Layers):
  for j in range (Base_Branch_Length+1):
    tree_map_'i'.append(0)
    tree_map_'i'.insert(0, 0)

如果用户说5层和5个基本分支长度,列表将显示:

tree_map_5 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]
tree_map_4 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]
tree_map_3 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]
tree_map_2 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]
tree_map_1 = [0, 0, 0, 0, 0, B, 0, 0, 0, 0, 0]

我想知道是否能够编写一个for循环,根据它们输入的层的数量,将0添加到数量可变的列表中(就像我尝试的那样)。你知道吗

对不起,我的问题不清楚。你知道吗

谢谢


Tags: the用户intreemapforinputyour
1条回答
网友
1楼 · 发布于 2024-10-05 10:22:44

查看this article以掌握动态变量名。就像文章已经警告过的那样,不应该使用动态变量bames。如果您坚持这样做,那么在for循环中,您应该将.append(0).insert(0,0)分别替换为以下内容:

globals()['tree_map_{}'.format(i)].append(0)
globals()['tree_map_{}'.format(i)].insert(0, 0)

但更好的解决方案是使用一个大列表:

Layers = int(input("\nHow many layers will your christmas tree have? (Maximum 5)\n\nInput: "))
Base_Branch_Length = int(input("\nHow long will the base branches of your tree be? (in centimetres)\n\nInput: "))

tree_map = [['B'] for i in range(Layers)]

for i in range (Layers):
  for j in range (Base_Branch_Length+1):
    tree_map[i].append(0)
    tree_map[i].insert(0, 0)

print(tree_map[0])

相关问题 更多 >

    热门问题