繁体   English   中英

在不完全展平的情况下扩展 Python 中的嵌套列表

[英]Expanding Nested lists in Python without fully flattening

假设我有一个包含嵌套列表的列表,例如字符串:

items = ['Hello', ['Ben', 'Chris', 'Linda'], '! The things you can buy today are', ['Apples', 'Oranges']]

我想要一个字符串列表,将嵌套列表组合并展平为所有可能性,这样的结果是:

new_list = ['Hello Ben ! The things you can buy today are Apples',
            'Hello Ben ! The things you can buy today are Oranges',
            'Hello Chris ! The things you can buy today are Apples',
            'Hello Chris ! The things you can buy today are Oranges',
            'Hello Linda ! The things you can buy today are Apples',
            'Hello Linda ! The things you can buy today are Oranges',]

我一直在查看 itertools 文档,但没有按预期正常工作。 我不想对迭代进行硬编码,因为这个项目列表可以在项目数量和嵌套列表数量之间变化。

例如:

list(itertools.chain(*items))

将展平列表,但它会拆分字符串项中的各个字符。 部分挑战在于列表中的某些项目是字符串,而其他项目是附加列表。 将不胜感激任何帮助。 谢谢

你需要itertools.product()

这是实际操作:

>>> items = [['Hello'], ['Ben', 'Chris', 'Linda']]
>>> list(itertools.product(*items))
[('Hello', 'Ben'), ('Hello', 'Chris'), ('Hello', 'Linda')]

由于itertools.product()将列表列表作为输入,因此您的代码中需要进行一些转换以将'Hello'转换为['Hello'] -

import itertools
items = ['Hello', ['Ben', 'Chris', 'Linda'], '! The things you can buy today are', ['Apples', 'Oranges']]
new_items = itertools.product(*[item if isinstance(item, list) else [item] for item in items])
new_list = [' '.join(x) for x in new_items]

new_list

['Hello Ben ! The things you can buy today are Apples',
 'Hello Ben ! The things you can buy today are Oranges',
 'Hello Chris ! The things you can buy today are Apples',
 'Hello Chris ! The things you can buy today are Oranges',
 'Hello Linda ! The things you can buy today are Apples',
 'Hello Linda ! The things you can buy today are Oranges']

你可以用回溯来解决:

def test(itm):
    n = len(itm)
    results = []
    def dfs(idx, res):
        if idx == n:
            results.append(res.copy())
            return
        if isinstance(itm[idx], list):
            for d in itm[idx]:
                res.append(d)
                dfs(idx+1, res)
                res.pop()
        else:
                res.append(itm[idx])
                dfs(idx+1, res)
                res.pop()

    dfs(0, [])
    return results

output:

test(items)

[['Hello', 'Ben', '! The things you can buy today are', 'Apples'],
 ['Hello', 'Ben', '! The things you can buy today are', 'Oranges'],
 ['Hello', 'Chris', '! The things you can buy today are', 'Apples'],
 ['Hello', 'Chris', '! The things you can buy today are', 'Oranges'],
 ['Hello', 'Linda', '! The things you can buy today are', 'Apples'],
 ['Hello', 'Linda', '! The things you can buy today are', 'Oranges']]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM