简体   繁体   中英

Cast each digit of string to int

So I have a string say "1234567", and my desired endpoint is a list of the form [1, 2, 3, 4, 5, 6, 7]

What I'm currently doing is this

[int(x) for x in "1234567"]

What I'm wondering is if there is a better or more Pythonic way to do this? Possibly using built-ins or standard library functions.

You can use map function:

map(int, "1234567")

or range :

range(1,8)

With range result will be same:

>>> map(int, "1234567")
[1, 2, 3, 4, 5, 6, 7]
>>> range(1,8)
[1, 2, 3, 4, 5, 6, 7]

One way is to use map. map(int, "1234567")

There isn't any 'more pythonic' way to do it. And AFAIK, whether you prefer map or list comprehension is a matter of personal taste, but more people seem to prefer list comprehensions.

For what you are doing though, if this is in performance-sensitive code, take a page from old assembly routines and use a dict instead, it will be faster than int , and not much more complicated:

In [1]: %timeit [int(x) for x in '1234567']
100000 loops, best of 3: 4.69 µs per loop

In [2]: %timeit map(int, '1234567')
100000 loops, best of 3: 4.38 µs per loop

# Create a lookup dict for each digit, instead of using the builtin 'int'
In [5]: idict = dict(('%d'%x, x) for x in range(10))

# And then, for each digit, just look up in the dict.
In [6]: %timeit [idict[x] for x in '1234567']
1000000 loops, best of 3: 1.21 µs per loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM