这是我做的 -
grid_len = input("Enter Grid Length: ") //Assuming grid_length to be 3
s = []
while True:
s.append(input())
if len(s) == int(grid_len)**2: //grid_length^2 will be 9
print(s)
break
当输入在第一个循环中为例如1时,在第二个循环中为2,在第三个循环中为3,依此类推至9;它会创建一个这样的列表:
['1','2','3','4','5','6','7','8','9']
但我想要这样的事情:
[[1,2,3],[4,5,6],[7,8,9]]
答案 0 :(得分:4)
基于列表理解的版本。
s = [[input("Enter number: ") for _ in range(grid_len)] for _ in range(grid_len)]
print s
注意:两个正斜杠“//”不是有效的python注释标识符
答案 1 :(得分:2)
我从这个问题找到的东西:How do you split a list into evenly sized chunks?
>>> mylist = [1,2,3,4,5,6,7,8,9]
>>> def chunks(l, n):
... return [l[i:i+n] for i in range(0, len(l), n)]
>>> chunks(mylist,3)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
集成到您的代码中:
def chunks(l, n):
return [l[i:i+n] for i in range(0, len(l), n)]
grid_len = input("Enter Grid Length: ")
s = []
while True:
s.append(int(input())) # Notice I put int() around input()
if len(s) == int(grid_len)**2:
s = chunks(s,grid_len)
print(s)
break
编辑:更改了块中的第二个参数以匹配grid_len
。现在这不仅适用于3。
答案 2 :(得分:1)
这是我的代码:
grid_len = input("Enter Grid Length: ")
s = []
for i in range(grid_len): #looping to append rows
s.append([]) #append a new row
for j in range(grid_len): #looping to append cells
s[-1].append(input()) #append a new cell to the last row, or you can also append to `i`th row
答案 3 :(得分:1)
尝试一下:
arr = [list(map(int, input().split())) for i in range(int(input()))]
答案 4 :(得分:0)
您应该为每个grid_length
元素创建一个新的子列表:
grid_len = int(input("Enter Grid Length: "))
s = []
for _ in range(grid_length):
sub_list = []
for _ in range(grid_length):
sub_list.append(input())
s.append(sub_list)
print(s)
请注意,通常,每次必须在对象上顺序迭代或者您知道重复循环的次数时,应使用for
。 while
通常更好地处理难以考虑迭代次数或迭代迭代次数的“奇怪”条件。
答案 5 :(得分:0)
使用嵌套列表推导:
>>> grid_len = input("Enter Grid Length: ")
Enter Grid Length: 4
>>> incrementer = iter(xrange(1, grid_len ** 2 + 1))
>>> s = [[next(incrementer) for x in xrange(grid_len)] for y in xrange(grid_len)]
>>> print s
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
答案 6 :(得分:0)
试试这个:
x = [[int(input()) for c in range(grid_len)] for r in range(grid_len)]
答案 7 :(得分:0)
我遇到了您的问题,非常简单的解决方法是
grid_length = int(input())
s = []
for i in range(grid_length):
b = input().split()
for i in range(len(b)):
b[i] = int(b[i]) #for converting into integers
s.append(b)
print(s)
答案 8 :(得分:0)
试试这个:
grid_len = int(input()) #just one input
grid = [[input(),input(),input()] for _ in range(grid_len)] #grid_len * 3 inputs
print(grid)