2015-11-08 123 views
1

我正在尋找一個變體來確定字符串列表中的字符(「b」)是否遵循使用嵌套循環的特定字符(「a」)。然後程序應該計算上述爲真的字符串總數。帶有嵌套循環的列表中的元素比較

我寫了下面的代碼,使用.find

nStrings = int (input ("input n amount of strings: ")) 

listStr = [ ] 

sumStr = 0 

for i in range (0, len(nStrings)): 

    newStr = input ("enter string: ") 

    listn.append(newStr) 

for i in range (0, len(listStr)): 

    if listn[i].find("a") < listn[i].find("b"): 

     sumStr = sumStr + 1 

print("sumStr") 

但是對我的作品,我正在尋找一種方式與嵌套循環做到這一點。

我的做法是目前

for i in range (0, len(listStr)): 

    if listStr[i] == "a": 

     foundA = i 

     for j in range (i+1, len(listStr)): 

       if list[j] == "b": 

        foundB = j 

       if foundA < foundB: 

        afterA = True 

然而,這不適合我在所有的工作。如果嘗試了幾個變體,但我確信我正在犯一個邏輯錯誤。

+2

你應該減少你的問題,「檢查單個字符串,無論是一個字符cter出現在另一個字符之前「。然後,當你這樣做時,你將這個解決方案應用到一個字符串列表中。你已經在你的第一個解決方案中做了這種類型的事情,但在你的第二個問題中,你正在混淆事物:你正在迭代字符串列表,期望列表中的單個成員是字符。 – poke

+1

爲什麼你想要爲這個問題使用嵌套循環?你想避免'str.find()'? – Jasper

+0

@賈斯珀,正確的,尋找一種方法來取代在這種情況下查找 –

回答

0

下面是函數的實現,以檢查在字符串a後是否b發生:

def a_before_b(haystack): 
    found_a = False 
    for letter in haystack: 
    if letter == 'a': 
     found_a = True 
    elif letter == 'b' and found_a: # we found 'b' and already have found 'a' earlier 
     return True 

    return False 

爲了避免.find(),而不是使用行

if listn[i].find("a") < listn[i].find("b"): 
在你的代碼

這種方法,像這樣:

if a_before_b(listn[i]): 
0

我不會使用嵌套for循環進行這種比較,而不是可以使用str.find()方法(其中,因爲@ cricket_007指出的那樣,是一個隱含循環):

def getinput(): 
    nStrings = int(input("inuput n amount of strings:")) 
    l = [] 
    for i in range(nStrings): 
    l.append(input('enter string\n')) 
    return l 
def compare(itm): 
    if 'a' in itm and 'b' in itm: 
    return True if itm.find('a') < itm.find('b') else False 
    else: 
    return None 

listStr = getinput() 
print zip(listStr, map(compare, listStr)) 

的給定的輸入:['David', 'alphabet', 'bagpipes'],這應該返回元組的列表:

[('David', None), ('alphabet', True), ('bagpipes', False)] 
+0

'str.index'是一個隱含的循環在整個字符串... –

+0

這是同樣的事情,它只是返回-1而不是錯誤,如果子字符串未找到。 –

+0

@ cricket_007如果你有一個修改,以改善這一點,請隨時進行修改。否則,我不知道你要求我做什麼...... –

0

您可以使用一個循環

letter1 = "a" 
letter2 = "b" 
for i in range (0, len(listStr)): 
    if listStr[i] == letter1: 
     pos1 = i 
    if listStr[i] == letter2: 
     pos2 = i 

foundAfter = (pos2 > pos1) # an error is here if the letters weren't found at all 
+0

@poke len(listStr)== 0,除非有更多的代碼,OP沒有向我們展示... –

+0

@DavidZemens - 他只是在糾正你的語義。你是正確的大聲笑:) –

+0

@ cricket_007,如果一個字符串[我]包含多個字符,條件== letter1不會返回一個值,即「abc」!=「a」 –