2014-12-20 56 views
0

我目前正在做一些作業,我在其中加載了兩個文本文件,每個文件都帶有200個名稱,分成兩個不同的列表,一個男孩的名字和一個女孩的名字女孩的名字,因爲我還沒有完成男孩的名字)。 我想要求用戶輸入一個名稱,然後顯示該名稱的流行程度。所以我使用切片將列表中的前50個名稱設置爲流行,並將最後50個名稱設置爲不流行。然而,在if語句中,無論輸入什麼內容,它總是會進入else子句。將boyList [0-51]設置爲popularBoys顯然有些問題,但我不確定是什麼,或者如何解決它。Python列表切片找不到輸入用'in'運算符

def main(): 
    openBoyFile = open('BoyNames.txt', 'r') 
    readBoyNames = openBoyFile.readlines() 
    openBoyFile.close() 

    boyList = [readBoyNames] 

    #remove \n 
    index = 0 
    while index < len(readBoyNames): 
     readBoyNames[index] = readBoyNames[index].rstrip('\n') 
     index += 1 

    print('Boy names: ', boyList) 


    openGirlFile = open('GirlNames.txt', 'r') 
    readGirlNames = openGirlFile.readlines() 
    openGirlFile.close() 

    girlList = [readGirlNames] 

    index2 = 0 
    while index2 < len(readGirlNames): 
     readGirlNames[index2] = readGirlNames[index2].rstrip('\n') 
     index2 += 1 

    print('') 
    print('Girl names: ', girlList) 



    popularBoys = boyList[0:51] 
    notSoPopularBoys = boyList[52:151] 
    totallyNotPopularBoys = boyList[152:200] 

    print('') 
    boyNameInput = input('Enter a boy name to check how popular it is: ') 

    if boyNameInput in popularBoys: 
     print('The name entered is among the 50 most popular!') 

    elif boyNameInput in notSoPopularBoys: 
     print('The name entered is not so pouplar. Among 51 - 150 on the list.') 

    elif boyNameInput in totallyNotPopularBoys: 
     print('The name entered is not popular at all. Among 151-200 on the list.') 

    else: 
     print('Not a name on the list.') 


main() 
+0

根據您的描述,這不可能是您的問題,但請注意Python切片'[a:b]'返回索引在'a'的元素直到幷包括'b-1',而不是'b '。 – xnx

回答

3

問題是這兩行:

boyList = [readBoyNames] 
girlList = [readGirlNames] 

readBoyNamesreadGirlNames已經列出。您正在創建一個包含另一個列表的列表。 如果更改這兩個行

boyList= readBoyNames 
girlList= readGirlNames 

它的工作原理,沒有任何問題。