python - 如何将嵌套的字符串列表转换为一个列表?
问题描述
我想将嵌套的字符串列表转换为单个列表。例如,如果有一个类似的列表,
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
有解决方法吗?提前致谢。
解决方案
见下文(假设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']
推荐阅读
- php - get_post_meta()不显示wordpress循环中第一项的字段值
- android - 无法在华为设备中显示通知
- flutter - 升级到 macOS Catalina 后将颤振路径从 .bash_profile 更改为 .zprofile
- python - 如何从最后一个“。”之后的字符串中删除最后一个字符
- c++ - 将 FreeType GlyphSlot 位图转换为 Vulkan BGRA
- r - 嵌套 ifelse 函数是否有 R 函数?
- python - 如何将此 python 行代码转换为列表理解?
- matlab - 在matlab中增加生成的文本文件中的有效数字
- c# - 如何将数据添加到 SQLite 离线数据库表并在 listView Xamarin 上显示
- python - 如何获得按 numpy 和 pandas 中的变量分组的平均值?