2016-08-01 76 views
0

我有一個簡單的列表分裂問題:分裂列表理解成嵌套的列表根據規則

給出一個嵌套列表如下:

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

我想進一步分裂的任何元素(子列表)超過3,並且其長度爲3或者3 N + 1爲長度爲3分名單,除了最後一個塊的倍數,所以結果我想要的是:

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

我認爲它可以用itertools.groupby完成d /或產量的功能......但不能放在一起詳情>> 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] 

任何人都可以請給我一些指點?非常感謝。

+0

對於列表不能被3整除,他們如何處理...? –

+0

另外,http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python?rq=1。 –

+0

@ g.d.d.c,感謝您的回覆! 3n + 2的值保留,因爲它們是...並非常感謝你的鏈接!當我剛剛重新編輯時,我意識到我的問題有點牽涉到...... – shenglih

回答

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]] 
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]]