开发者_如何学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.
精彩评论