2013-03-13 162 views
2

以下是我did-列表清單列表:如何根據用戶輸入列出清單列表?

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

您可以通過用戶想每輸入3個創建一個列表?然後將這些列表中的每一個嵌入到另一個列表中? – 2013-03-13 08:58:49

+2

順便說一句,Python中的註釋以散列符號('#')而不是'//'開頭:p – TerryA 2013-03-13 09:00:01

+0

@Haidro謝謝,但我已經知道了。 – 2013-03-13 09:30:30

回答

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通常更好地處理難以根據迭代次數或迭代遍歷迭代的「奇怪」條件。

+0

它在這一行中給我這個錯誤:for _ in range(grid_len): TypeError:'str'對象不能被解釋爲整數 – 2013-03-13 09:36:39

+0

@yesboy對不起,我太習慣python2了。我更新了代碼以將大小轉換爲整數。 – Bakuriu 2013-03-13 12:49:23

3

基於列表理解的版本。

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

注:雙斜線 「//」 是無效的蟒蛇評論標識符

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

0

試試這個工作:

x = [[int(input()) for c in range(grid_len)] for r in range(grid_len)] 
0

這裏是我的代碼:

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