gpt4 book ai didi

python - 如何从给定条件开始获取列表中的元素

转载 作者:行者123 更新时间:2023-11-28 21:35:34 25 4
gpt4 key购买 nike

我的代码是:

 b=[1215316235,1215316234,1210216096,1210716053]
for i in range(398):
a=b[i]
if a[0:5] == '12153':
print(a)

我收到错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-113-d3b104ffc744> in <module>()
1 for i in range(398):
2 a=b[i]
----> 3 if a[0:5] == '12153':
4 print(a)

TypeError: 'int' object is not subscriptable

如何获得预期的输出:

1215316235
1215316234

最佳答案

为了使您的逻辑正常工作,您需要在切片之前转换为 str。此外,您应该迭代值而不是范围,例如通过对列表进行切片。

更有效的方法是使用列表理解。以下是一些示例:

b = [1215316235, 1215316234, 1210216096, 1210716053]

import math

b = b*10000

%timeit [x[:5] == '12153' for x in map(str, b)] # 22.4 ms per loop
%timeit [str(x)[:5] == '12153' for x in b] # 28.1 ms per loop
%timeit [x // 10**(int(math.log10(x))-4) == 12153 for x in b] # 48.6 ms per loop

关于python - 如何从给定条件开始获取列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52099416/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com