今天下午我很无聊。我如何转换
['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']
进入
[1,9,3,10,5,8,8,11,2,7,4,5,2,6]
?
今天下午我很无聊。我如何转换
['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']
进入
[1,9,3,10,5,8,8,11,2,7,4,5,2,6]
?
>>> L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']
>>> [int(y) for x in L for y in x.split(',')]
[1, 9, 3, 10, 5, 8, 8, 11, 2, 7, 4, 5, 2, 6]
这个嵌套列表推导等效于:
res = []
for x in L:
for y in x.split(','):
res.append(int(y))
如您所见,自上而下的结构在列表推导中从左到右
IE。
[int(y)
for x in L
for y in x.split(',')]
解开的现在看起来与for
循环相同。
另一种方式:
>>> [int(x) for x in ','.join(L).split(',')]
[1, 9, 3, 10, 5, 8, 8, 11, 2, 7, 4, 5, 2, 6]
看到有几种不同的方法可以做到这一点,我决定运行一些(快速)测试,看看哪个是最快的。
python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']" "[int(x) for x in ''.join(L).split(',')]"
>>> 100000 loops, best of 3: 3.2 usec per loop
python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']" "[int(y) for x in L for y in x.split(',')]"
>>> 100000 loops, best of 3: 6.38 usec per loop
python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6'];from itertools import chain" "[int(x) for x in chain.from_iterable(l) if x != ',']"
>>> 100000 loops, best of 3: 6.68 usec per loop
好像[int(x) for x in ''.join(L).split(',')]
拿了蛋糕。
编辑:按照 jamylak 的建议,我添加了以下测试:
python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']" "map(int, ''.join(L).split(','))"
>>> 100000 loops, best of 3: 2.79 usec per loop
python -m timeit -s "L = ['1,9', '3,10', '5,8', '8,11', '2,7', '4,5', '2,6']" "list(map(int, ''.join(L).split(',')))"
>>> 100000 loops, best of 3: 3.02 usec per loop
所以map(int, ''.join(L).split(','))
或者list(map(int, ''.join(L).split(',')))
对于 python3 是最好的方法。