检查字符串是否可以在Python中表示为数字的最佳方法是什么?
我目前拥有的功能是:
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
Run Code Online (Sandbox Code Playgroud)
这不仅是丑陋而且缓慢,似乎很笨重.但是我没有找到更好的方法,因为调用floatmain函数更糟糕.
这两个代码片段之间有什么区别?使用type():
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
Run Code Online (Sandbox Code Playgroud)
使用isinstance():
if isinstance(a, dict):
do_something()
if isinstance(b, str) or isinstance(b, unicode):
do_something_else()
Run Code Online (Sandbox Code Playgroud) 我需要知道Python中的变量是字符串还是字典.以下代码有什么问题吗?
if type(x) == type(str()):
do_something_with_a_string(x)
elif type(x) == type(dict()):
do_somethting_with_a_dict(x)
else:
raise ValueError
Run Code Online (Sandbox Code Playgroud)
更新:我接受了avisser的回答(但如果有人解释为什么isinstance更喜欢,我会改变主意type(x) is).
但由于nakedfanatic提醒我,这是经常清洁剂使用的字典(作为case语句)比如果/ elif的/其他系列.
让我详细说明我的用例.如果变量是一个字符串,我需要将它放在一个列表中.如果它是一个字典,我需要一个唯一值的列表.这是我想出的:
def value_list(x):
cases = {str: lambda t: [t],
dict: lambda t: list(set(t.values()))}
try:
return cases[type(x)](x)
except KeyError:
return None
Run Code Online (Sandbox Code Playgroud)
如果isinstance是首选,你会怎么写这个value_list()功能?
给定一个任意python对象,确定它是否是数字的最佳方法是什么?这里is定义为acts like a number in certain circumstances.
例如,假设您正在编写矢量类.如果给出另一个向量,您想要找到点积.如果给定标量,则需要缩放整个向量.
检查,如果事情是int,float,long,bool很烦人,不包括可能像数字用户定义的对象.但是,__mul__例如,检查是不够好的,因为我刚才描述的矢量类会定义__mul__,但它不是我想要的那种数字.
例如,我想检查一个字符串,如果它不能转换为整数(with int()),我该如何检测?
python ×5
types ×3
casting ×1
converter ×1
inheritance ×1
int ×1
numbers ×1
oop ×1
string ×1
typechecking ×1