首页 > 解决方案 > 如何使用某些条件重新组合嵌套列表?

问题描述

我试图建立一些线性连接,我有一些清单:

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]

我首先重组bbb

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

bb再次尝试重新组合,标准是 when cs[u[i]][u[i+1]] > 3,将其重新组合为另一个子列表。

u是子列表bb

i是指数u

所以期望的输出是:

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

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

对于 , 中的第三个子列表bbcs[0][1] < 3 and cs[1][2] >3因此将其重新组合为 [0,1],[2]

如何进入outputpython?

标签: pythonlistfunction

解决方案


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

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


推荐阅读