我怎样才能打开以下列表
['1','2','A,B,C,D','7','8']
进入
['1','2','A','B','C','D','7','8']
以最蟒蛇的方式?
我有非常 unpythonic 的代码创建嵌套列表,然后奉承:
sum ( [ word.split(',') for word in words ], [] )
result = [item for word in words for item in word.split(',')]
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']
k=k=['1','2','A,B,C,D','7','8']
m=[i for v in k for i in v if i!=","]