首页 > 解决方案 > python:拆分每个子列表中的项目

问题描述

我有以下子列表:

lst=[['a,b,c,d,e'],['f,g,h'] ]

我想获得以下结果:

lst=[['a','b','c','d','e'],['f','g','h']]

但以下行

lst1=[y for x in lst for y in x.split(',')]
print(lst1)

产生此错误: AttributeError: 'list' object has no attribute 'split'

我应该如何解决这个问题?

标签: pythonsplitsublist

解决方案


试试这个简单的方法:

lst = [['a,b,c,d,e'],['f,g,h']]

list1 = [x[0].split(',') for x in lst]
print(list1)

输出: [['a', 'b', 'c', 'd', 'e'], ['f', 'g', 'h']]


推荐阅读