如何根据用户输入创建列表?

2024-04-25 23:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

这就是我所做的-

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

Tags: totrueinputlenifbelengthgrid
3条回答

基于列表理解的版本

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

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

这是我的密码:

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

我从这个问题中发现: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年

相关问题 更多 >