我对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添加到数量可变的列表中(就像我尝试的那样)。你知道吗
对不起,我的问题不清楚。你知道吗
谢谢
查看this article以掌握动态变量名。就像文章已经警告过的那样,不应该使用动态变量bames。如果您坚持这样做,那么在for循环中,您应该将.append(0)和.insert(0,0)分别替换为以下内容:
但更好的解决方案是使用一个大列表:
相关问题 更多 >
编程相关推荐