如何打开以下列表
['1','2','A,B,C,D','7','8']
到
['1','2','A','B','C','D','7','8']
以最蟒蛇的方式?
我有非常unpythonic的代码创建嵌套列表,然后flatterens:
sum ( [ word.split(',') for word in words ], [] )
答案 0 :(得分:19)
result = [item for word in words for item in word.split(',')]
答案 1 :(得分:3)
In [1]: from itertools import chain
In [2]: lis=['1','2','A,B,C,D','7','8']
In [5]: list(chain(*(x.split(',') for x in lis)))
Out[5]: ['1', '2', 'A', 'B', 'C', 'D', '7', '8']
进一步减少不需要的split()
来电:
In [7]: list(chain(*(x.split(',') if ',' in x else x for x in lis)))
Out[7]: ['1', '2', 'A', 'B', 'C', 'D', '7', '8']
使用map()
:
In [8]: list(chain(*map(lambda x:x.split(','),lis)))
Out[8]: ['1', '2', 'A', 'B', 'C', 'D', '7', '8']
In [9]: list(chain(*map(lambda x:x.split(',') if ',' in x else x,lis)))
Out[9]: ['1', '2', 'A', 'B', 'C', 'D', '7', '8']
答案 2 :(得分:0)
k=k=['1','2','A,B,C,D','7','8']
m=[i for v in k for i in v if i!=","]