检查字符串是否可以在Python中表示为数字的最佳方法是什么?
我目前拥有的功能是:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Run Code Online (Sandbox Code Playgroud)
这不仅是丑陋而且缓慢,似乎很笨重.但是我没有找到更好的方法,因为调用floatmain函数更糟糕.
我有一个来自MySQL查询的元组元组,如下所示:
T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
Run Code Online (Sandbox Code Playgroud)
我想将所有字符串元素转换为整数并将它们放回列表列表中:
T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
Run Code Online (Sandbox Code Playgroud)
我试图实现它,eval但没有得到任何体面的结果.
有没有办法判断一个字符串是否代表一个整数(例如'3','-17'但不是'3.14'或'asfasfas')没有使用try/except机制?
is_int('3.14') = False
is_int('-7') = True
Run Code Online (Sandbox Code Playgroud) Stack Overflow 上有很多关于这个一般主题的问答,但它们要么质量很差(通常是初学者的调试问题暗示的),要么以其他方式错过了目标(通常是不够通用)。至少有两种极其常见的方法会使幼稚的代码出错,初学者从关于循环的规范中获益更多,而不是从将问题作为拼写错误或关于打印所需内容的规范中获益。所以这是我尝试将所有相关信息放在同一个地方。
假设我有一些简单的代码,可以对一个值进行计算x并将其分配给y:
y = x + 1
# Or it could be in a function:
def calc_y(an_x):
return an_x + 1
Run Code Online (Sandbox Code Playgroud)
现在我想重复计算 的许多可能值x。我知道for如果我已经有要使用的值列表(或其他序列),我可以使用循环:
xs = [1, 3, 5]
for x in xs:
y = x + 1
Run Code Online (Sandbox Code Playgroud)
while或者,如果有其他逻辑来计算值序列,我可以使用循环x:
def next_collatz(value):
if value % 2 == 0:
return value // 2
else:
return 3 * value + 1
def collatz_from_19():
x = 19
while x != 1:
x …Run Code Online (Sandbox Code Playgroud)