You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表处理:如何拆分多类型条目为单类型元素列表?

实现方法

要把原有的电影类型列表展开为单个类型元素的列表,用Python可以这样做:

步骤说明

  • 遍历原列表中的每个字符串条目
  • 对每个条目按逗号,拆分,得到单个类型的子列表
  • 去除每个类型字符串前后的空格(原条目里类型间带空格,拆分后会残留,需要清理)
  • 将所有拆分后的类型合并成一个新列表

代码示例

# 原电影类型列表
movie_genres = ['Action, Adventure, Thriller', 'Comedy, Drama, Romance', 'Adventure, Drama, Romance', 'Crime, Drama', 'Drama, Thriller, War', 'Animation, Adventure, Comedy']

# 展开为单个类型的列表
expanded_genres = [genre.strip() for item in movie_genres for genre in item.split(',')]

# 打印结果
print(expanded_genres)

输出结果

运行代码后会得到你需要的格式:

['Action', 'Adventure', 'Thriller', 'Comedy', 'Drama', 'Romance', 'Adventure', 'Drama', 'Romance', 'Crime', 'Drama', 'Drama', 'Thriller', 'War', 'Animation', 'Adventure', 'Comedy']

补充说明

如果不习惯用列表推导式,也可以用普通循环实现,逻辑完全一致:

expanded_genres = []
for item in movie_genres:
    # 拆分每个条目并清理空格
    genres = [g.strip() for g in item.split(',')]
    # 将拆分后的类型批量添加到结果列表
    expanded_genres.extend(genres)

内容的提问来源于stack exchange,提问作者Laro19

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 21:40:16