如何将列表中的整数仅拆分为个位数? [英] How do a split integers within a list into single digits only?
本文介绍了如何将列表中的整数仅拆分为个位数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有这样的东西:
list(range(9:12))
哪个给我一个列表:
[9,10,11]
但是我希望它像这样:
[9,1,0,1,1]
哪个整数将每个整数都拆分为一个数字,在不牺牲过多性能的情况下是否有实现这一目标的方法?还是有一种首先生成此类列表的方法?
Which splits every integer into single digits, is there anyway of achieving this without sacrificing too much performance? Or is there a way of generating list like these in the first place?
推荐答案
You can build the final result efficiently without having to build one large and/or small intermediate strings using itertools.chain.from_iterable
.
In [18]: list(map(int, chain.from_iterable(map(str, range(9, 12)))))
Out[18]: [9, 1, 0, 1, 1]
In [12]: %%timeit
...: list(map(int, chain.from_iterable(map(str, range(9, 20)))))
...:
100000 loops, best of 3: 8.19 µs per loop
In [13]: %%timeit
...: [int(i) for i in ''.join(map(str, range(9, 20)))]
...:
100000 loops, best of 3: 9.15 µs per loop
In [14]: %%timeit
...: [int(x) for i in range(9, 20) for x in str(i)]
...:
100000 loops, best of 3: 9.92 µs per loop
计时与输入成比例. itertools 版本还有效地使用内存,尽管与list(map(int, ...))
一起使用时,它比str.join
版本略慢:
Timings scale with input. The itertools version also uses memory efficiently although it is marginally slower than the str.join
version if used with list(map(int, ...))
:
In [15]: %%timeit
...: list(map(int, chain.from_iterable(map(str, range(9, 200)))))
...:
10000 loops, best of 3: 138 µs per loop
In [16]: %%timeit
...: [int(i) for i in ''.join(map(str, range(9, 200)))]
...:
10000 loops, best of 3: 159 µs per loop
In [17]: %%timeit
...: [int(x) for i in range(9, 200) for x in str(i)]
...:
10000 loops, best of 3: 182 µs per loop
In [18]: %%timeit
...: list(map(int, ''.join(map(str, range(9, 200)))))
...:
10000 loops, best of 3: 130 µs per loop
这篇关于如何将列表中的整数仅拆分为个位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文