我想在Python中检查数字的前两位。如下所示:
for i in range(1000):
if(first two digits of i == 15):
print("15")
elif(first two digits of i == 16):
print("16")
有没有检查数字前两位的命令?我希望避免使用像if(i>149 and i<160):...
这样的命令
发布于 2018-02-10 08:33:39
前面两个答案的时间复杂度都至少为O(n),字符串转换的空间复杂度也为O(n)。这是一个恒定时间和空间的解决方案:
num // 10 ** (int(math.log(num, 10)) - 1)
功能:
import math
def first_n_digits(num, n):
return num // 10 ** (int(math.log(num, 10)) - n + 1)
输出:
>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456
您将需要添加一些检查,如果您的输入号码可能比您想要的数字少。
发布于 2016-12-22 04:44:24
您可以使用正则表达式测试匹配项并捕获前两位数字:
import re
for i in range(1000):
match = re.match(r'(1[56])', str(i))
if match:
print(i, 'begins with', match.group(1))
正则表达式(1[56])
匹配后跟5或6的1,并将结果存储在第一个捕获组中。
输出:
15 begins with 15
16 begins with 16
150 begins with 15
151 begins with 15
152 begins with 15
153 begins with 15
154 begins with 15
155 begins with 15
156 begins with 15
157 begins with 15
158 begins with 15
159 begins with 15
160 begins with 16
161 begins with 16
162 begins with 16
163 begins with 16
164 begins with 16
165 begins with 16
166 begins with 16
167 begins with 16
168 begins with 16
169 begins with 16
https://stackoverflow.com/questions/41271299
复制相似问题