首页 > 解决方案 > 如何将嵌套的字符串列表转换为一个列表?

问题描述

我想将嵌套的字符串列表转换为单个列表。例如,如果有一个类似的列表,

fruits = ['apple','orange, ['pineapple','grapes']]

我想将其转换为:

fruits = ['apple','orange','pineapple','grapes']

我尝试使用,more_itertools.chain.from_iterable(fruits)但我得到的输出是:

['a','p','p','l','e','o','r','a','n','g','e','pineapple','grapes']

即使尝试过[inner for item in fruits for inner in item],这也给出了与上面相同的输出。

我也试过[inner for item in fruits for inner in ast.literal_eval(item)],但这给出了一个错误ValueError: malformed string

有解决方法吗?提前致谢。

标签: pythonpandaslistdataframemore-itertools

解决方案


见下文(假设fruits仅包含字符串或列表)

fruits = ['apple', 'orange', ['pineapple', 'grapes']]
flat = []
for f in fruits:
    if isinstance(f, str):
        flat.append(f)
    else:
        flat.extend(f)
print(flat)

输出

['apple', 'orange', 'pineapple', 'grapes']

推荐阅读