原始猫看起来像这样:
cat = ['a','a,b,c','c,d,e,f']
我想将其转换为:
cat = [['a'],['a','b','c'],['c','d','e','f']]
答案 0 :(得分:4)
您可以通过list comprehension
实现此目的:
>>> cat = ['a','a,b,c','c,d,e,f']
>>> [c.split(',') for c in cat]
[['a'], ['a', 'b', 'c'], ['c', 'd', 'e', 'f']]
另外,您也可以使用lambda
函数与map
实现此目的:
>>> map(lambda x: x.split(','), cat)
[['a'], ['a', 'b', 'c'], ['c', 'd', 'e', 'f']]
答案 1 :(得分:2)
您只需要split每个字符串:
result = [s.split(',') for s in cat]
答案 2 :(得分:1)
试试这个:
cat = ['a','a,b,c','c,d,e,f']
newlist = [a.split(',') for a in cat]
print(newlist)
>>> [['a'], ['a', 'b', 'c'], ['c', 'd', 'e', 'f']]