查詢級別:初級Python列表和列表項匹配 - 我的代碼/推理可以改進嗎?
作爲一個學習練習,我已經寫代碼,必須檢查是否一個字符串(因爲它是通過的raw_input建立)的任何列表項的開始處匹配,以及它是否任何列表項的一部分。
wordlist = ['hello', 'bye']
handlist = []
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
for item in wordlist:
if item.startswith(hand):
while item.startswith(hand):
if hand not in wordlist:
letter = raw_input('enter letter: ')
handlist.append(letter)
hand = "".join(handlist)
else: break
else: break
print 'you loose'
此代碼的作品,但我的代碼(和我的推理/方法)如何改進? 我有這種感覺,我的嵌套IF
,WHILE
和FOR
陳述是矯枉過正。
編輯 感謝戴夫,我能夠大大縮短和優化我的代碼。
wordlist = ['hello','hamburger', 'bye', 'cello']
hand = ''
while any(item.startswith(hand) for item in wordlist):
if hand not in wordlist:
hand += raw_input('enter letter: ')
else: break
print 'you loose'
我很驚訝,我原來的代碼工作在所有...
+1任何。不知道。 (*今天學點新東西* - 支票) – 2010-09-22 11:41:58
@ Space_C0wb0y - 還有'all()':http://docs.python.org/library/functions.html#all – 2010-09-22 11:50:28
我會在明天騰出一個:) – 2010-09-22 12:01:25