基于规则将列表理解拆分为嵌套列表

时间:2016-08-01 16:00:14

标签: python list

我有一个简单的列表拆分问题:

给出一个这样的嵌套列表:

x = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]]

我想进一步将任何长度超过3的元素(子列表)和长度为3或3n + 1的倍数拆分成长度为3的子列表,除了最后一个块,所以我想要的结果是:

x2 = [[1,4,3], [2,3,5],[1,3,52],[3,5,2,1],[2]]

我认为可以使用itertools.groupby和/或yield函数来完成...但是无法将详细信息放在一起>> a_function(x)......

 splits = [ a_function(x) if len(x)>3 and (len(x) % 3 == 0 or len(x) % 3 == 1) else x for x in x]

有人可以给我一些指示吗?非常感谢。

2 个答案:

答案 0 :(得分:0)

有时候,当列表理解的要求不寻常或复杂时,我会使用生成器函数,如下所示:

def gen(l):
   for sublist in l:
       if len(sublist)%3 == 0:
           for i in range(0, len(sublist), 3):
               yield sublist[i:i+3]
       elif len(sublist)%3 == 1:
           for i in range(0, len(sublist)-4, 3):
               yield sublist[i:i+3]
           yield sublist[-4:]
       else:
           yield sublist

# OP's data:
x = [[1,4,3],[2,3,5,1,3,52,3,5,2],[2]]
y = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]]

# Using either list comprehension or list constructor:
newx = [item for item in gen(x)]
newy = list(gen(y))

# Result:
assert newx == [[1, 4, 3], [2, 3, 5], [1, 3, 52], [3, 5, 2], [2]]
assert newy == [[1, 4, 3], [2, 3, 5], [1, 3, 52], [3, 5, 2, 1], [2]]

答案 1 :(得分:0)

# Create the list 
x = [[1,4,3],[2,3,5,1,3,52,3,5,2,1],[2]] 
test = []
# Loop through each index of the list
for i in range(len(x)):
#if the length of the specific index is 3 then go do this loop. 
    if len(x[i]) > 3:
        j = len(x[i])
        # This cuts through the loop every 3 steps and makes it a new list. 
        test = ([x[i][j:j+3] for j  in range(0, len(x[i]), 3)])
        # If the length of the last index is 1 then add it to the previous index of the new list. 
        if len(test[-1]) == 1: 
                test[-2] = test[-2] + test[-1]
                # pop deletes the last entry
                test.pop(-1)
                x[i] = test 
        else:
            x[i] = test 

然后你得到输出:

[[1, 4, 3], [[2, 3, 5], [1, 3, 52], [3, 5, 2, 1]], [2]]