开发者

Looking for a snippet to convert a string into a list of integers

开发者_如何学JAVAAs an example:

>> s = '0123456' 
>> list(s)
['0', '1', '2', '3', '4', '5', '6']

I have come up with this:

>> map( lambda x:int(x), list(s) )
[0, 1, 2, 3, 4, 5, 6]

Can this be improved ?


Just use a list comprehension, or if appropriate a generator expression. Simple, and a bit faster (arguably) more readable.

[int(x) for x in s]


>>> map(int, ['1', '2'])
[1, 2]

>>> map(int, '123')
[1, 2, 3]


There is nothing really wrong with your approach except it is not necessary to convert the string into a list since strings are iterables.

>>> s = '0123456' 
>>> map(lambda x:int(x), s)
[0, 1, 2, 3, 4, 5, 6]

If you prefer the list comprehension/iterator see @zeekay's answer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜