我正在制作一个用户输入决策树,我想强制将输入进行比较的字典改为小写。我把.lower()放在不同的地方并且不断出错。
not_found = True
while True:
if OPTIONS == "1" or 'a':
ARTIST_PICK = str(raw_input(
"Please pick an artist\n"
"Or Q to quit: ")).lower
print ARTIST_PICK
**entries = allData(filename).data_to_dict()
for d in entries:
arts = d['artist']**
if ARTIST_PICK in arts:
print "found it"
elif ARTIST_PICK == 'q':
break
else:
print "Sorry, that artist could not be found. Choose again."
not_found = False
这是我试图降低“条目”的示例,并将用户输入与以下内容进行比较:
[{'album': 'Nikki Nack', 'song': 'Find a New Way', 'datetime': '2014-12-03 09:08:00', 'artist': 'tUnE-yArDs'},]
答案 0 :(得分:1)
如果您的问题只是比较艺术家的名字,那么您可以使用列表理解来使所有内容都小写。
entries = allData(filename).data_to_dict()
if ARTIST_PICK in [ d['artist'].lower() for d in entries ]:
print("found it")
elif ARTIST_PICK == "q":
break
else
print("Sorry, that artist could not be found. Choose again.")
或者,如果您更倾向于使用for
循环(为了便于阅读而重新安排一点):
if(ARTIST_PICK != 'q'):
entries = allData(filename).data_to_dict()
found = False
for d in entries:
if ARTIST_PICK == d['artist'].lower():
found = True
break
elif ARTIST_PICK == "q":
break
if(found):
print("found it")
else:
print("Sorry, that artist could not be found. Choose again.")
else:
# handle the case where the input is 'q' here if you want
顺便说一下,作为一个原则问题,您应该将布尔变量命名为就像在句子中使用它们一样。如果找不到变量,请将变量not_found
设置为False
,而不是将名为found
的变量设置为False
或将not_found
设置为{ {1}}。从长远来看,事情会变得更容易。
答案 1 :(得分:0)
ARTIST_PICK = str(raw_input( “请选择一位艺术家\ n” “或者Q要退出:”))。lower()