[英]Force case on dictionary to compare user input in Python
我正在制作用戶輸入決策樹,我想強制將要比較輸入的字典轉換為小寫形式。 我在各個地方放置了.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'},]
如果您的問題只是比較藝術家的姓名,則可以使用列表推導使所有內容變為小寫。
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
循環(為便於閱讀而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
設置為True
。 從長遠來看使事情變得容易。
ARTIST_PICK = str(raw_input(“請選擇一個藝術家\\ n”“或Q退出:”))。lower()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.