7

我怎样才能打开以下列表

['1','2','A,B,C,D','7','8']

进入

['1','2','A','B','C','D','7','8']

以最蟒蛇的方式?

我有非常 unpythonic 的代码创建嵌套列表,然后奉承:

sum ( [ word.split(',') for word in words ], [] )
4

3 回答 3

19
result = [item for word in words for item in word.split(',')]
于 2012-10-09T21:09:22.230 回答
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']
于 2012-10-09T21:07:52.620 回答
0
      k=k=['1','2','A,B,C,D','7','8']
      m=[i for v in k for i in v if i!=","]
于 2012-11-08T17:27:19.760 回答