在循环中合并和删除列表中的元素

时间:2014-12-22 07:45:32

标签: python list merge

我想做这样的事情:

我有一个清单:

  pairs =  [1,1,1,1,0,0,2,2,2,2,0,3,3,3,3,0,0,0,0,0,4,4,4,4]

我找到了元素:

  frags =   [[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]  

现在我想要合并短于0的0的块:

[[1,1,1,1,0,0,2,2,2,2,3,3,3,3],[4,4,4,4]]

我试图这样做:

        while j < len(frags)-1:    # I added a 'terminator' before, so that len-1           
            stop_1 = pairs.index(frags[j][-1])
            start_1 = pairs.index(frags[j][0])
            start_2 = pairs.index(frags[j+1][0])
            stop_2 = pairs.index(frags[j+1][-1])
            island = float(start_2 - stop_1 - 1)
            if island < 4 :  
                frags[j] = pairs[start_1:stop_2+1]
                frags.remove(frags[j+1]) #the same iteration again
            else: j+=1 

但是如果我删除它们,我会得到无限循环,因为frag永远比len更短。 我该如何解决?

1 个答案:

答案 0 :(得分:0)

使用itertools.groupby,就像这样

from itertools import groupby

groups, temp = [], []
# Group items based on the actual values
for key, grp in groupby(pairs):
    grp = list(grp)
    # If it is a group of zeros and the size is >= 4
    if key == 0 and len(grp) >= 4:
        # Add the accumulated groups to the result
        groups.append(temp)
        # Make the accumulator free
        temp = []
    else:
        # If it is a group of non-zeros or zeros of size < 4,
        # extend the accumulated group
        temp.extend(grp)

if temp:
    groups.append(temp)

print(groups)
# [[1, 1, 1, 1, 0, 0, 2, 2, 2, 2, 0, 3, 3, 3, 3], [4, 4, 4, 4]]