我正在尝试接受用户输入,并检查它是否在词典中。 希望用户输入字符串,浮点数和整数,但是只有字符串才能正确比较。
搜索“ 5”返回有效,但是10或15.0都不起作用,因为将输入转换为字符串。
除了执行检查以强制用户指定他们要搜索的数据类型之外,还有没有办法做到这一点?
new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
print(search_term)
print(type(search_term))
for k,v in new_dict.items():
print(v)
if v == search_term:
do_something = True
print ('yes')
print(do_something)
提前谢谢!
答案 0 :(得分:1)
您可以做类似的事情:
new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
if v == int(search_term):
do_something = True
print("yes")
elif v == str(search_term):
do_something = True
print ('yes')
答案 1 :(得分:1)
只需将要比较的两个变量都转换为字符串:
new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
if str(v) == str(search_term):
do_something = True
print ('yes')
print(do_something)
另一种解决方案:
new_dict = {'a': '5', 'b':10, 'c':15.0}
do_something = False
search_term = input('enter term: ')
for k,v in new_dict.items():
try:
search_term = float(search_term)
v = float(v)
except:
pass
if v == search_term:
do_something = True
print ('yes')
print(do_something)
答案 2 :(得分:0)
用if v == search_term:
代替if repr(v) == search_term:
可以,它可以在'5'
上作为输入,但不能在"5"
上作为输入。