原貓看起來是這樣的:如何將列表元素轉換爲列表?
cat = ['a','a,b,c','c,d,e,f']
我想將其轉換爲:
cat = [['a'],['a','b','c'],['c','d','e','f']]
原貓看起來是這樣的:如何將列表元素轉換爲列表?
cat = ['a','a,b,c','c,d,e,f']
我想將其轉換爲:
cat = [['a'],['a','b','c'],['c','d','e','f']]
你只需要split每個字符串:
result = [s.split(',') for s in cat]
試試這個:
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']]
您可以通過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']]