python - 如何使用某些条件重新组合嵌套列表?
问题描述
我试图建立一些线性连接,我有一些清单:
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
再次尝试重新组合,标准是 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]
对于 , 中的第三个子列表bb
,cs[0][1] < 3 and cs[1][2] >3
因此将其重新组合为
[0,1],[2]
如何进入output
python?
解决方案
这并不漂亮,但这应该可以为您完成工作:
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]]
推荐阅读
- travis-ci - Travis-CI - 铬 62 而不是 77
- kotlin - 使用 by 委托给另一个相同类型的对象甚至不会编译
- python - 有什么方法可以在 django settings.py 中导入模型?
- javascript - 如何在查询参数中使用 plus 而不是 %20 和 vue 路由器?
- azure - Azure Webjob/函数重试计数
- python - __init__() 接受 2 个位置参数,但 3 个是使用 WebDriverWait 和 expected_conditions 作为 element_to_be_clickable 和 Selenium Python 给出的
- mysql - 插入查询是否需要三个引号?
- jsf - 在前端的下拉列表和搜索框中键入适当的搜索
- javascript - 如何在 alasql 中按日期配置查询条件。谷歌脚本 + AlaSql
- serialization - 无法序列化值。错误:格式错误的 UTF-8 字符,可能编码不正确