[英]I am trying to make there be a list within a list and then edit the number within the list within the list
我曾尝试做一个战舰程序,其中计算机随机生成 1 艘船的位置,但是当我尝试在由一个大列表中的 8 个列表组成的网格中将单个整数更改为 2 时,但无法做任何事情列表。
这是我到目前为止尝试过的代码:
import random
ocean = []
for index_1 in range(0, 8):
row = []
for index_2 in range(0, 8):
row.append(0)
ocean.append(row)
for index_3 in range(0,8):
xAxis = []
xAxis.append(random.randint(0,8))
yAxis = []
yAxis.append(random.randint(0,8))
nums = range(0,8)
for num in nums:
[ocean[yAxis[num]]] = 2
欢迎来到堆栈溢出。 我要指出几点:
在这个片段中:
for index_3 in range(0,8):
xAxis = []
xAxis.append(random.randint(0,8))
yAxis = []
yAxis.append(random.randint(0,8))
每次将随机 int 添加到列表之前,您都会循环并将 xAxis 和 yAxis 设置为空列表。 因此,在循环结束时,yAxis 和 xAxis 只有一个元素。
要修复它,请在循环之前移动xAxis = []
和yAxis = []
。
此外, randint(0, 8) 在返回中包括 start 和 end。 您需要 randint(0, 7) 以免索引超出范围。
下一个:
nums = range(0,8)
for num in nums:
[ocean[yAxis[num]]] = 2
在这里,yAxis 只有一个元素,但即使在你修复它之后,它也会抛出一个错误。 您将尝试做的是解压缩列表,但 2 不是列表。
[ocean[yAxis[num]]] = 2
与编写ocean[yAxis[num]], = 2
相同。 现在,
看起来格格不入。 因此,您可能正在寻找的是ocean[yAxis[num]] = 2
。
但是,作为海洋是[[0,0,0,0,..],[0,0,0,0,...],...]
,您可能不想设置其中之一元素为 2。您想将嵌套列表的元素之一设置为 2。
也许是这样的:
nums = range(0,8)
for num in nums:
ocean[xAxis[num]][yAxis[num]] = 2
所以海洋看起来像:
[
[0,0,2,0,0,2,0,0],
[0,0,2,0,0,0,0,0],
...
]
正如@IamFr0ssT 已经指出的那样,您在每次迭代时都会清空 xaxis 和 yaxis 。 并将船只分配到只有 y 轴的海洋。
更正上面,下面是一个完整的代码。
import random
ocean = [[0 for _ in range(8)] for _ in range(8)]
ship_locations = [[random.randint(0,8-1),random.randint(0,8-1)] for _ in range(0,8)]
for location in ship_locations:
ocean[location[0]][location[1]]=2
print(ocean)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.