[英]how to write print output within a for loop to a list in python?
我已将所有代码用于上下文。 基本上它应该根据用户选择的路线打印一个向量列表。 就目前而言,它将向量打印到屏幕上,如下所示:
[12, 2]
[12, 3]
[11, 3]
...
...
这是我需要的,但是,我还希望将打印的向量按打印顺序写入列表,以便稍后调用它们,即 vector_list = [[12, 2], [12, 3], 11, 3]]....
我对此很陌生,并且正在学习,所以感谢您的耐心等待。 下面将创建一个名为 vector_list 的列表,但它只会一遍又一遍地保存相同的向量,即 [12, 2]。 我认为我的问题是我正在使用 .append? 我最初想尝试类似 vector_list = vector_list + x 但它说 vector_list 没有定义?
else:
print(start)
vector_list.append(start)
vectors()
print(vector_list)
完整代码供参考:
route001 = (3, 12, 'S', 'S', 'W', 'S', 'S', 'S', 'E', 'E', 'E', 'S', 'S', 'W',
'W', 'S', 'E', 'E', 'E', 'E', 'N', 'N', 'N', 'N', 'W', 'N', 'N',
'E', 'E', 'S', 'E', 'S', 'E', 'S', 'S', 'W', 'S', 'S', 'S', 'S',
'S', 'E', 'N', 'E', 'E')
route002 = (12, 11, 'W', 'W', 'S', 'S', 'S', 'W', 'W', 'N', 'N', 'N', 'W', 'W',
'W', 'S', 'S', 'S', 'S', 'E', 'E', 'S', 'W', 'W', 'W', 'W', 'N', 'N',
'W', 'W', 'S', 'S', 'S', 'S', 'E', 'E', 'E', 'S', 'E', 'S', 'E', 'S')
route003 = (3, 12, 'S', 'S', 'W', 'S', 'S', 'S', 'W', 'W', 'W', 'S', 'S', 'W',
'W', 'S', 'E', 'E', 'E', 'E', 'N', 'N', 'N', 'N', 'W', 'N', 'N', 'E',
'E', 'S', 'E', 'S', 'E', 'S', 'S', 'W', 'S', 'S', 'S', 'S', 'S', 'E',
'N', 'E', 'E')
route_selection = input('Select route 1, 2 or 3 ')
if route_selection == "1":
selectedRoute = route001
elif route_selection == "2":
selectedRoute = route002
elif route_selection == "3":
selectedRoute = route003
else:
print("error")
start = [selectedRoute[0]] + [selectedRoute[1]]
directions = selectedRoute[2:]
coordinates = {"N": [0, 1], 'E': [1, 0], 'S': [0, -1], 'W': [-1, 0]}
vector_list = []
def vectors():
for d in directions:
dx, dy = coordinates[d]
start[0] += dx
start[1] += dy
if start[0] < 0 or start[0] > 12:
print('Error: This route goes outside the grid')
break
elif start[1] < 0 or start[1] > 12:
print('Error: This route goes outside the grid')
break
else:
print(start)
vector_list.append(start)
vectors()
print(vector_list)
您也可以尝试循环打印它们。 像这样的东西。
对于 vector_list 中的向量: print(vector) // 或 print(vector, end=',')
问题是 list 是 Python 中的一个可变对象(我假设你不知道那是什么,我鼓励你谷歌一下:)
基本上这意味着,当您将列表附加到“向量列表”时,它不会复制该列表并存储在向量列表中,它(非常粗略地说,不是那么准确)保留指向列表的指针并将其存储在向量列表中
当您更改列表时,向量列表中的所有条目都会更改,因为它们指向您附加的同一个列表
因此,例如,您可以做的是复制该列表并将其存储在“向量列表”中
只需更改此行: vector_list.append(start)
至: vector_list.append(start.copy())
它应该可以工作,可能有一种更有效的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.