首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按int值将嵌套列表拆分为子列表

按int值将嵌套列表拆分为子列表
EN

Stack Overflow用户
提问于 2019-05-13 19:26:04
回答 2查看 540关注 0票数 1

我有两份名单:

代码语言:javascript
复制
 data = [[1,2,3,4], [5,6,7], [8,9,10,11,12,13,14]]
 splitters = [3,7,10,13]

我希望使用以下条件将数据中的嵌套列表按拆分器中的值拆分:

  1. 如果它是列表中的第一个/最后一个值,不要拆分。
  2. 拆分器中的拆分值应该位于新列表开头的的末尾。
  3. 应该是可迭代的,因此列表被分割成与列表中的拆分器一样多的部分。
  4. 没有冗余。

最终的结果应该是:

代码语言:javascript
复制
results = [[1,2,3],[3,4],[5,6,7],[8,9,10],[10,11,12,13],[13,14]

我的第一次尝试是这样的:

代码语言:javascript
复制
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])

临时工看起来是这样的:

代码语言:javascript
复制
[[[1, 2, 3, 4], 0],
 [[1, 2, 3, 4], 0],
 [[1, 2, 3, 4], 3],
 [[1, 2, 3, 4], 0],...]

在此基础上,我可以删除多余的路由并分割路由,但我认为我的方法不必要地复杂,如果我想要实现一些满足其他条件的东西,就会变得越来越混乱。

到目前为止,我的研究还没有成功(使用itertools.groupby等)。这是有关联的:values/

将欣赏一些想法/方法如何解决这个问题或细分它在较小的部分。

面向未来读者的编辑:--我更喜欢maxiotic的解决方案,因为它甚至可以处理类似的数据。

代码语言:javascript
复制
data = [[1,2,3],[1,2,3,4,5,6,7]]
splitters = [1,2,3,4,7]

嵌套列表的每个开始/结束都在拆分器中。Relondom解决方案中的问题是以下if语句,必须更改:

代码语言:javascript
复制
    if inner[0] in splitters or inner[-1] in splitters:  # check if first or last elemtn in splitters

非常感谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-13 20:20:12

下面是我正在研究的解决方案:

代码语言:javascript
复制
results = []
for route in data:
    found = 0
    for idx, r in enumerate(route[1:-1], 1):  # start idx at 1
        if r in splitters:
            temp = route[found:idx+1]  # +1 to capture the splitter value
            results.append(temp)
            found = idx 
    remaining = route[found:]
    results.append(remaining)
票数 0
EN

Stack Overflow用户

发布于 2019-05-13 19:47:36

我不知道这是否是一种最佳的方法,但我决定编写这段代码,因为还没有人回答。

代码语言:javascript
复制
res = []
for inner in data:
    if inner[0] in splitters or inner[-1] in splitters:  # check if first or last elemtn in splitters
        res.append(inner) 
        continue
    else:
        temp = []  
        for val in inner:
            if val not in splitters:
                temp.append(val)
            else:
                temp.append(val)  # list ends with value from splitters
                res.append(temp)  # add new list to result
                temp = [val]  # new list starts with value from splitters
        if temp not in res:
            res.append(temp)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56118707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档