【问题标题】:Merging and removing elements from list in a loop在循环中合并和删除列表中的元素
【发布时间】:2014-12-22 07:45:32
【问题描述】:

我想做这样的事情:

我有一个清单:

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

现在我想合并小于 4 的 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 短。 我该如何解决?

【问题讨论】:

  • 预期输出中的23 之间不应该有0 吗? [1,1,1,1,0,0,2,2,2,2,0,3,3,3,3]?

标签: python list merge


【解决方案1】:

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

【讨论】:

  • 你认为我可以将碎片的全局副本作为“循环范围”(而 j
  • 请注意,如果pairs 以四个或更多零开头,这将生成一个空列表作为第一个元素。即[0,0,0,0] -> [[]]。另外,这是relevant link to groupby
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 2017-02-08
相关资源
最近更新 更多