使用循环将坐标存储在嵌套列表中

时间:2019-05-22 12:33:24

标签: python list

我拥有一个机器人的坐标,我将机器人的数量作为 输入坐标并将其存储在称为位置的列表中。我希望位置存储所有机器人的坐标。

使用循环,我在位置内添加一个空列表,并将坐标存储到子列表中。

locations = []

m = input("Number of robots: ")

for i in range(m)
    locations.append([])

    x = x + 1
    y = y + 1
    z = z + 1
    locations[i].append(x)
    locations[i].append(y)
    locations[i].append(z) 
print(locations)

我希望结果是位置[(1,1,1),(2,2,2)....],但是我无法获得输出。

7 个答案:

答案 0 :(得分:0)

为什么要先附加一个空列表,然后再添加内容?

locations = []
x = y = z = 0

m = input("Number of robots: ")

for i in range(m):
  x = x + 1
  y = y + 1
  z = z + 1

  locations.append([x, y, z])

print(locations)

答案 1 :(得分:0)

尝试一下

locations = []
m = input("Number of robots: ")
for i in range(1, m+1): # This starts from 1 and print till m(m+1 is to consider "m")
    locations.append((i,i,i)) # This will create your desired output.
print(locations)

答案 2 :(得分:0)

这应该有效:

locations = []

m = input("Number of robots: ")

for i in range(int(m)):
    x += 1
    y += 1
    z += 1
    locations.append([x, y, z])

print(locations)

答案 3 :(得分:0)

尝试一下

locations = []
x = y = z = 0

m = input("Number of robots: ")

for i in range(m):
  x = x + 1
  y = y + 1
  z = z + 1

  locations.append((x, y, z))

print(locations)

答案 4 :(得分:0)

要验证输入,您可以使用isdecimal()

m = -1
while m < 0:
    inp = input("Number of robots: ")
    if inp.isdecimal():
        m = int(inp)
    else:
        print("Invalid input.")

要使用元组创建新列表,我建议您将列表理解与sequence repetition一起使用。

locations = [(i,) * 3 for i in range(1, m + 1)]
print(locations)

输出:

Number of robots: word
Invalid input.
Number of robots: 5
[(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 4, 4), (5, 5, 5)]

答案 5 :(得分:0)

尝试一下:

locations = []

m = int(input("Number of robots: "))
x, y, z = 0, 0, 0
for i in range(m):
    x, y, z = x + 1, y + 1, z + 1
    locations.append([x, y, z])
print(locations)

您的代码中有一些错误:

  • for in in range之后的冒号
  • 缺少输入到整数的转换。

更好的是,您可以使用简单的list comprehension

locations = [[i, i, i] for i in range(int(input("Number of robots: ")))]

答案 6 :(得分:0)

我知道您已经有很多答案了,但是只是想翻阅一下原始代码,然后看看发生了什么:

autoPlay

有了这些更改,我收到的输出是: [[1,1,1],[2,2,2],[3,3,3],[4,4,4]]

正如其他人指出的那样,不需要附加一个空列表,您可以删除该空列表附加行,并用以下简单的代码替换其他附加代码行:

locations = []

m = input("Number of robots: ")

# You're missing a colon here
# Also, since m was user input, it's actually of type string
# You could use the 'int' function around it to make it an integer
for i in range(int(m)):

    locations.append([])

    # x, y and z are not defined, though I'm assuming you've done this elsewhere
    x = x + 1
    y = y + 1
    z = z + 1
    locations[i].append(x)
    locations[i].append(y)
    locations[i].append(z)

print(locations)

那么您的输出如下,我认为这是您的初衷: [(1,1,1),(2,2,2),(3,3,3),(4,4,4)]