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

将列表拆分为嵌套列表
EN

Stack Overflow用户
提问于 2020-12-26 13:23:44
回答 4查看 230关注 0票数 1

我有一个嵌套列表,我正试图将其拆分为嵌套在原始列表中的较小的列表。我要用一个特定的元素来划分列表。我已经知道了这个部分,但是当我试图迭代原始列表时,却只返回了最后一个列表。

代码语言:javascript
复制
animals  = [["animal", "cat", "dog", "bird", "animal", "cat", "snake", "bird"], 
     ["animal", "cat", "iguana", "bird", "animal", "lizard", "dog", "bird"]]

for n in animals:
    it  = iter(n)
    combined = [[next(it)]]
    for ele in it:
        if ele != "animal":
            combined[-1].append(ele)
        else:
            combined.append([ele])
    
print combined

输出:

[例][“动物”,“猫”,“蜥蜴”,“鸟”,“动物”,“蜥蜴”,“狗”,“鸟”)

期望产出:

[“动物”、“猫”、“狗”、“鸟”、“动物”、“猫”、“蛇”、“鸟”、“动物”、“猫”、“蜥蜴”、“鸟”、“动物”、“蜥蜴”、“狗”、“鸟”)

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2020-12-26 13:38:07

试试这个丙酮溶液:

代码语言:javascript
复制
str_ = ' '.join([a for animal in animals for a in animal])
list_of_animals = [['animal']+st.split() for st in str_.split("animal") if len(st)>1]

它提供了所需的输出。

票数 2
EN

Stack Overflow用户

发布于 2020-12-26 13:35:49

代码语言:javascript
复制
animals  = [["animal", "cat", "dog", "bird", "animal", "cat", "snake", "bird"], ["animal", "cat", "iguana", "bird", "animal", "lizard", "dog", "bird"]]

result = []
for row in animals:
    result_row = []
    for element in row:
        if element == "animal":
            if result_row:
                result.append(result_row)
            result_row = []
        result_row.append(element)
    result.append(result_row)
print(result)
票数 0
EN

Stack Overflow用户

发布于 2020-12-26 13:48:59

由于animals的结构可能是不规则的,这可能是一个解决方案:

代码语言:javascript
复制
from itertools import groupby

combined = [
    ['animal'] + list(group)
    for sublist in animals
    for key, group in groupby(sublist, key=lambda s: s == 'animal') if not key
]

输出:

代码语言:javascript
复制
[['animal', 'cat', 'dog', 'bird'],
 ['animal', 'cat', 'snake', 'bird'],
 ['animal', 'cat', 'iguana', 'bird'],
 ['animal', 'lizard', 'dog', 'bird']]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65456839

复制
相关文章

相似问题

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