我有一个简单的列表拆分问题:
给定如下嵌套列表:
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]
有人能给我一些建议吗?非常感谢。
有时,当列表理解的要求不寻常或复杂时,我会使用生成器函数,比如:
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]]
# 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]]