【问题标题】:How to combine and create a list with certain criteria to a nested list in python?python - 如何将具有特定条件的列表组合并创建到python中的嵌套列表?
【发布时间】:2019-03-12 09:24:28
【问题描述】:

我有两个清单:

a = [0,0,2,2,2,2]
b = [1,3,2,3,6,7]

A和b相互关联,a[i]关联b[i]我想得到

c = [[0,1,3],[2,2,3],[2,6,7]]

a = 0时,b中有两个值与0相关,即b[0],b[1],所以将它们连接为c的第一个inner-list,

a=2时,有4个值与2相关,即b[2],b[3],b[4],b[5],但b[3]b[4]之间的差距大于3,所以@987654338 @stop as [2,2,3] 并创建一个连接a == 2b[3],b[4],b[5] 的新列表

所以我的标准是当b[i],b[i+1].... 都与a 的特定值相关但它们之间存在>= 3 的差距时,首先创建一个列表[a[i],b[i]],然后将其他列表结合起来。我被它困住了。

【问题讨论】:

    标签: python-3.x list nested counter


    【解决方案1】:

    首先根据a创建组:

    c = zip(a, b)
    
    c = {k: [bi for ai, bi in g] for k, g in groupby(c, lambda i: i[0])}
    

    现在连接到列表列表(按顺序):

    c = [v for k, v in sorted(c.items())]
    

    现在你需要一个函数来按值差距分割:

    def split_max_gap(l, max_gap=2):
        acc = [l[0]]
        for x, y in zip(l, l[1:]):
            if abs(x - y) > max_gap:
                yield acc
                acc = [y]
                continue
            acc.append(y)
        if acc:
            yield acc
    

    将拆分应用于上一个列表:

    c = map(split_max_gap, c)
    

    展平:

    c = list(chain.from_iterable(c))
    

    c 现在应该持有:

    [[1, 3], [2, 3], [6, 7]]
    

    【讨论】:

      【解决方案2】:

      你写的

      b[3]和b[4]的差距大于3

      但不是更大。大于等于。

      a = [0, 0, 2, 2, 2, 2]
      b = [1, 3, 2, 3, 6, 7]
      c = []
      
      for s in set(a):
          i = a.index(s)
          count = a.count(s)
          pom = []
      
          for j in range(i, i + count):
              if not pom:
                  pom.append(b[j])
              elif abs(pom[-1] - b[j]) < 3:
                      pom.append(b[j])
                      if j + 1 == count:
                          pom.insert(0, s)
                          c.append(pom)
                          pom = []
                      else:
                          pom.insert(0, s)
                          c.append(pom)
                          pom = [b[j]]
      
      print(c)
      

      【讨论】:

        猜你喜欢
        • 2011-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 1970-01-01
        相关资源
        最近更新 更多