我需要知道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()功能?