2014-12-08 62 views
1

我有這個函數可以將前三列數據附加到一個新的空列表中。示例輸出:Python將多個列表添加到列表中

['red', 'blue', 'green', 'yellow', 'purple', 'black'] 

我想這個列表的每兩個元素包圍在自己的名單即

[['red', 'blue'], ['green', 'yellow'], ['purple', 'black']] 

我怎樣才能做到這一點?謝謝。

def selection_table(table): 
    atts = [1,2,3] 
    new_table = [] 
    for row in table: 
     for i in range(len(new_atts)): 
      new_table.append(row[atts[i]]) 
    return new_table 

回答

1
>>> my_list = ['red', 'blue', 'green', 'yellow', 'purple', 'black'] 
>>> result = (my_list[i:i+2] for i in range(0, len(my_list), 2)) 
>>> list(result) 
[['red', 'blue'], ['green', 'yellow'], ['purple', 'black']] 
+0

非常感謝! – shutoutzilla37 2014-12-08 07:16:53

2

你可以在this問題:

a = ['red', 'blue', 'green', 'yellow', 'purple', 'black'] 

def chunks(l, n): 
    """ Yield successive n-sized chunks from l. 
    """ 
    for i in range(0, len(l), n): 
     yield l[i:i+n] 

print(list(chunks(a, 2)))  

給出:

[['red', 'blue'], ['green', 'yellow'], ['purple', 'black']] 
+0

謝謝!我非常感謝! – shutoutzilla37 2014-12-08 07:17:11

0

簡單的方法就是使用拉鍊:)

test=['red', 'blue', 'green', 'yellow', 'purple', 'black'] 
c=zip(test[0::2],test[1::2]) 
map(lambda x :list(x),c) 
>>>>[['red', 'blue'], ['green', 'yellow'], ['purple', 'black']] 

test=['red', 'blue', 'green', 'yellow', 'purple', 'black'] 
map(lambda x :list(x),zip(test[0::2],test[1::2])) 
+0

實際上,如果他想得到列表而不是列表的列表,正確的答案是:'[list(x)for zip in zip(test [0 :: 2],test [1 :: 2]) ]' – bosnjak 2014-12-08 07:28:57

+0

@ shutoutzilla37試試這個答案 – 2014-12-08 07:35:19