我有这个函数可以将前三列数据附加到一个新的空列表中。示例输出为:
['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
答案 0 :(得分: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']]
答案 1 :(得分: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']]
答案 2 :(得分:0)
简单的方法是使用zip:)
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']]
OR
test=['red', 'blue', 'green', 'yellow', 'purple', 'black']
map(lambda x :list(x),zip(test[0::2],test[1::2]))