2017-12-02 32 views
0

私はイントロのPythonのクラスにいる新しいリストに同じ最初と最後の文字を持っているものを追加し、この割り当て与えられました。リスト内の文字列を比較し、

文字列のリストを考えると、返します元のリストから同じ文字で始まり、終わるすべての文字列を含む新しいリスト。マッチングは大文字小文字を区別しません。つまり、 'a'は 'A'と一致する必要があります。どのような方法でも元のリストを変更しないでください。

可能なリストに ''(空の文字列)が含まれているため、文字列をスライスして比較する際に問題が発生しました。私はかなり困惑しており、どんな助けもありがたいです。

だから、
def first_last(strings): 
    match=[] 
    x='' 
    count=0 
    while count<len(strings): 
     if x[0] == x[-1]: 
     match.append(x) 
     x+=x 
     count+=1 

、与えられた:

['aba', 'dcn', 'z', 'zz', ''] 

または

['121', 'NbA', '898', ''] 

を、私はこの取得:私が見てする必要がある場合には

string index out of range 

を:

['aba', 'z', 'zz'] 

['121', '898'] 

答えて

1

あなたのリストが空の文字列('')が含まれています。したがって、現在反復処理中の各要素の長さをチェックする必要があります。リストの要素がどれも最初でない場合

s = ['aba', 'dcn', 'z', 'zz', ''] 
final_strings = [i for i in s if i and i[0].lower() == i[-1].lower()] 
+0

私の無知を許しますが、あなたは[count]と書いたときに何を指していますか? –

0
def first_last(strings): 
    match=[] 
    for x in strings: 
     if x is '' continue; 
     if x.lower()[0] == x.lower()[-1]: 
     match.append(x) 
    return match 
0

テスト:あなたは、リストの内包表記を使用することができ、しかし、

def first_last(strings): 
    match=[] 
    count=0 
    while count<len(strings): 
     if strings[count]: 
     if strings[count][0].lower() == strings[count][-1].lower(): 
      match.append(strings[count]) 

     count += 1 
    return match 

注:また、あなたがxを使用することは思えません。

def first_last(strings): 
    match = [] 
    for element in strings: 
     if element and element[0].lower() == element[-1].lower(): 
      match.append(element) 
    return match 

またはリストコンプと