今天下午我很无聊。我该如何转换
['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]
答案 0 :(得分:4)
>>> 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))
如您所见,自上而下的结构在列表理解
中从左向右即
[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]
答案 1 :(得分:1)
看到有几种不同的方法可以做到这一点我决定运行一些(快速)测试,看看哪个是最快的。
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
因此,python3的map(int, ''.join(L).split(','))
或list(map(int, ''.join(L).split(',')))
是最好的方法。