Python列表切片找不到带有'in'op的输入

2024-04-25 23:15:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在做一些家庭作业,我在两个文本文件中加载了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()

Tags: thenameindexis名字printpopularindex2
1条回答
网友
1楼 · 发布于 2024-04-25 23:15:59

问题在于这两条线:

boyList = [readBoyNames]
girlList = [readGirlNames]

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

boyList= readBoyNames
girlList= readGirlNames

它工作没有问题。你知道吗

相关问题 更多 >