【问题标题】:How to regroup a nested list with certain criteria?如何使用某些条件重新组合嵌套列表?
【发布时间】:2019-03-29 14:22:04
【问题描述】:

我尝试做一些线性连接,我有一些列表:

cs = [[1,2,3,4],[1,2,4,5],[1,2,6,7],[3,4,5,6]]

b = [1,2,0,2,0,1,2]

我首先将b重组为bb

bb = [[1,2],[0,2],[0,1,2]]

我又尝试重新组合bb,标准是什么时候 cs[u[i]][u[i+1]] > 3,将其重新组合为另一个子列表。

ubb 中的子列表

iu的索引

所以欲望输出是:

output = [[1],[2],[0,2],[0,1],[2]]

对于bbcs[1][2] =4 和 >3 中的第一个子列表,将其重新组合为[1],[2]

对于bb中的第三个子列表,cs[0][1] < 3 and cs[1][2] >3,所以重新组合为 [0,1],[2]

如何在python中获取output

【问题讨论】:

    标签: python list function


    【解决方案1】:

    这并不漂亮,但这应该可以为您完成工作:

    cs = [[1,2,3,4],[1,2,4,5],[1,2,6,7],[3,4,5,6]]
    bb = [[1,2],[0,2],[0,1,2]]
    # Make a copy of bb
    cc = bb.copy()
    # Set an index offset
    ci = 0
    # Iterate through list bb and alter cc if condition is met
    for i in range(len(bb)):
        for j in range(len(bb[i])-1):
            if cs[bb[i][j]][bb[i][j+1]]>3:
    # Insert the latter part of bb[i] at i+ci+1 before changing the value at i+ci 
                cc.insert(i+ci+1, bb[i][j+1:])
                cc[i+ci] = list(bb[i][:j+1])
    # Increase the index offset by 1
                ci+=1
    cc
    

    我从中得到的输出是: [[1], [2], [0, 2], [0, 1], [2]]

    【讨论】:

      猜你喜欢
      • 2017-01-07
      • 2018-11-25
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 2015-02-10
      • 1970-01-01
      相关资源
      最近更新 更多