2010-09-22 29 views
2

查詢級別:初級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,WHILEFOR陳述是矯枉過正。

編輯 感謝戴夫,我能夠大大縮短和優化我的代碼。

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' 

我很驚訝,我原來的代碼工作在所有...

回答

8

首先,你不需要handlist變量;您只需連接raw_inputhand的值即可。

您可以通過啓動while環路與hand爲空字符串保存第一raw_input因爲每個字符串有startswith("")True

最後,我們需要找出最佳方法,看看wordlist中的任何項目是否以hand開頭。我們可以用一個列表理解爲這樣的:

[item for item in wordlist if item.startswith(hand)] 

,然後如果大於零檢查返回列表的長度。

然而,更妙的是,Python有the any() function這是完美的:它返回True如果一個迭代的任何元素爲True,所以我們只是評估startswith()wordlist每個成員。

把所有這些組合起來,我們得到:

wordlist = ['hello', 'bye'] 
hand = "" 

while any(item.startswith(hand) for item in wordlist): 
    hand += raw_input('enter letter: ') 
print 'you loose' 
+1

+1任何。不知道。 (*今天學點新東西* - 支票) – 2010-09-22 11:41:58

+1

@ Space_C0wb0y - 還有'all()':http://docs.python.org/library/functions.html#all – 2010-09-22 11:50:28

+0

我會在明天騰出一個:) – 2010-09-22 12:01:25