2017-01-31 7 views
0
def startsWith (word, lst): 
    u=0 
    x=0 
    w=len(word) 
    while u < len(lst): 
     lest = lst[u] 
     while x < len(word): 
      if word[x].lower() == lest[x]: 
       x=x+1 
      if word[x].upper() == lest[x]: 
       x=x+1 

     print (lst[u]) 
     u=u+1 

特定のリスト項目が「単語」文字列と同じ文字で始まるかどうかを確認したいものです。私は試運転を試みるたびに、いつも言っている場合:ループの問題python 3

>>> startsWith ('app',['apple','Apple','APPLE','pear','ApPle']) 
Traceback (most recent call last): 
    File "<pyshell#92>", line 1, in <module> 
    startsWith ('app',['apple','Apple','APPLE','pear','ApPle']) 
    File "C:/Users/gpersaud/Desktop/hw3.py", line 35, in startsWith 
    if word[x].upper() == lest[x]: 
IndexError: string index out of range 

答えて

1

第2のXは、単語

if word[x].upper() == lest[x]: 

と交換しての最後に到達した最後のものの後に x値を持っているかどう
if word[x].lower() == lest[x]: 
    x=x+1 
elif word[x].upper() == lest[x]: 
    x=x+1 

または

if word[x].lower() == lest[x] or word[x].upper() == lest[x]: 
    x=x+1 
+0

よりコンパクトな比較は、 'word [x] .upper()== lest [x] .upper()'です(これらのメソッドは両方とも単一の文字ではなく文字列全体で機能するので、それらは長い部分文字列にあります)。他にも潜在的な問題があります。 'lest'が' word'よりも短い場合、あなたは 'IndexError'を取得します。そして、 'x'は決して' 0'にリセットされません。したがって、最初の後のほとんどのリスト項目は、いくつかの中央の文字だけがチェックされます(リストの中で最長の項目よりも短いものは、まったくチェックされません)。あなたが文字でループする必要があるなら、私は 'for'ループと' zip'を使います。 – Blckknght