簡體   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