我有两张单子:
data = [[1,2,3,4], [5,6,7], [8,9,10,11,12,13,14]]
splitters = [3,7,10,13]
我想按splitter中的值拆分data中的嵌套列表,条件如下:
最终结果应该是:
results = [[1,2,3],[3,4],[5,6,7],[8,9,10],[10,11,12,13],[13,14]
我的第一次尝试是这样的:
temp = []
for route in data:
for node in route:
if node in splitter and ((route.index(node) !=0) and (route.index(node) != (len(route)-1))):
#route should be splitted and save it for now with the splitter
temp.append([route, node])
#here a big part is missing
#start a new subroute
#maybe something like a whileloop with len(route)
#check the same if-statement for the remaining subroute
else:
#no splitter in this route, so keep the original route
temp.append([route, 0])
温度看起来是这样的:
[[[1, 2, 3, 4], 0],
[[1, 2, 3, 4], 0],
[[1, 2, 3, 4], 3],
[[1, 2, 3, 4], 0],...]
基于此,我可以删除冗余路由并拆分路由,但是我认为我的方法不必要地复杂,如果我想实现一些东西来满足其他条件,它会变得越来越混乱。你知道吗
我的研究到目前为止还没有成功(使用itertools.groupby组等等)。这有点相关:https://www.reddit.com/r/learnpython/comments/3sk1xj/splitting_a_list_in_sublists_by_values/
如果您能提出一些解决这个问题或将其细分为更小的部分的想法/方法,我们将不胜感激。你知道吗
为未来读者编辑: 我更喜欢maxiotic的解决方案,因为它甚至可以处理这样的数据
data = [[1,2,3],[1,2,3,4,5,6,7]]
splitters = [1,2,3,4,7]
嵌套列表的每个开始/结束都在拆分器中。Relondom解决方案中的问题是以下if语句,必须更改:
if inner[0] in splitters or inner[-1] in splitters: # check if first or last elemtn in splitters
非常感谢!你知道吗
以下是我正在研究的解决方案:
我不知道这是否是一个最佳的方式,但我决定写这段代码,因为还没有人回答。你知道吗
相关问题 更多 >
编程相关推荐