Python列表切片没有找到输入' in'操作者

时间:2014-12-20 13:09:32

标签: python list file python-3.x slice

我正在做一些家庭作业,我加载了两个文本文件,每个文件有200个名字,两个不同的列表,一个男孩名字和一个女孩名字(忽略女孩的名字,因为我还没有完成男孩的名字然而)。 我想要求用户输入一个名称,然后显示该名称的受欢迎程度。所以我正在使用切片将列表中的前50个名称设置为流行,最后50个名称不受欢迎。但是在if语句中,无论输入什么,它总是转到else子句。将boyList [0-51]设置为popularBoys显然有问题但是我不确定是什么,或者如何修复它。

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()

1 个答案:

答案 0 :(得分:3)

问题是这两行:

boyList = [readBoyNames]
girlList = [readGirlNames]

readBoyNamesreadGirlNames已经是列表。您正在创建包含另一个列表的列表。 如果将这两行更改为

boyList= readBoyNames
girlList= readGirlNames

它没有任何问题。