将字符串的每一位都转换为in

2024-05-15 14:48:39 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个字符串说“1234567”,我想要的端点是一个表单列表[1,2,3,4,5,6,7]

我现在正在做的是

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

我想知道的是,是否有一个更好的或更Python的方式来做到这一点?可能使用内置或标准库函数。你知道吗


Tags: 字符串in表单列表for标准方式端点
3条回答

一种方法是使用地图。map(int, "1234567")

您可以使用map函数:

map(int, "1234567")

range

range(1,8)

与范围结果相同:

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

再没有比这更像Python的方法了。另外,不管你喜欢地图理解还是列表理解都是个人喜好的问题,但是更多的人似乎更喜欢列表理解。你知道吗

但是,对于您正在做的事情,如果这是在性能敏感的代码中,请从旧的程序集例程中获取一个页面并使用dict,它将比int更快,也不会更复杂:

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

相关问题 更多 >