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
相关产品推荐
相关产品推荐

