我有一个列表列表,我需要使用用户输入对元素进行分组(参见代码中的split
变量)并创建新列表。
我尝试过,而不是分组,元素是单独连接的
split = 3 # user input
data = [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14], [15,16], [17,18]]
z = [] ; y = []
for i,d in enumerate(data):
z.append(d)
if (i+1)%split==0:
y.append(z)
z = []
xx = (y+[z])
print(xx)
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]], [[13, 14], [15, 16], [17, 18]], []]
# ^____________________^ ^_______________________^ this needs to be merged
输入:
data = [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14], [15,16], [17,18]]
预期产出:
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]
答案 0 :(得分:3)
以下是使用列表理解的一种方法:
>>> sp = 3
>>> fragment = len(data)//sp
>>> [[t for item in data[i:i+fragment] for t in item] for i in range(0, len(data), fragment)]
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]
这是基于intertools的食谱:
>>> from itertools import islice, chain
>>>
>>> [list(chain.from_iterable(islice(data, i, i+fragment))) for i in range(0, len(data), fragment)]
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]
答案 1 :(得分:3)
你可以在基本的Python中这样做:
import itertools
flatlist = [*itertools.chain(*data)]
groupsize = int(len(flatlist) / split)
data2 = [flatlist[i:i+groupsize] for i in range(0, len(flatlist), groupsize)]
print(data2)
输出
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]
答案 2 :(得分:2)
使用numpy:
data = [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14], [15,16], [17,18]]
import numpy as np
print np.array(data).reshape((split,-1)).tolist()
输出:
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12], [13, 14, 15, 16, 17, 18]]
答案 3 :(得分:1)
你可以尝试这个 - >
split = 3
data = [[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [13,14], [15,16], [17,18]]
z=[]
x=[]
for i,j in enumerate(data):
if i!=0 and i%split==0:
z.append(x)
x=[]
for k in j:
x.append(k)
z.append(x)
print z
答案 4 :(得分:0)
您可以使用z.extend(d)
代替append