3

这就是我所做的-

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

例如,当 Input 在第一个循环中为 1,在第二个循环中为 2,在第三个循环中为 3,依此类推直到 9;它创建一个这样的列表:

['1','2','3','4','5','6','7','8','9']

但我想要这样的东西:

[[1,2,3],[4,5,6],[7,8,9]]
4

9 回答 9

5

基于列表理解的版本。

s = [[input("Enter number: ") for _ in range(grid_len)] for _ in range(grid_len)]
print s

注意:两个正斜杠“//”不是有效的python注释标识符

于 2013-03-13T09:07:54.867 回答
2

我从这个问题中发现了一些东西:如何将列表分成大小均匀的块?

>>> 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

编辑:将块中的第二个参数更改为 match grid_len。这现在不仅适用于 3。

于 2013-03-13T09:09:22.247 回答
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
于 2013-03-13T12:57:05.700 回答
1

尝试这个:

arr = [list(map(int, input().split())) for i in range(int(input()))]
于 2019-01-01T15:07:50.767 回答
1

我有你的问题,非常简单的解决方案是

grid_length = int(input())
s = []
for i in range(grid_length):
     b = list(map(int, input().split()))
     s.append(b)
print(s)
于 2018-12-15T12:07:09.913 回答
0

尝试这个:

x = [[int(input()) for c in range(grid_len)] for r in range(grid_len)]
于 2013-03-13T10:04:37.500 回答
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通常更好地处理难以考虑迭代次数或迭代迭代的“奇怪”条件。

于 2013-03-13T08:59:25.760 回答
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]]
于 2013-03-13T09:08:50.237 回答
0

尝试这个:

grid_len = int(input()) #just one input
grid = [[input(),input(),input()] for _ in range(grid_len)] #grid_len * 3 inputs
print(grid)
于 2021-07-16T15:55:54.247 回答