【问题标题】:Python list slicing not finding input with the 'in' operatorPython列表切片未使用“in”运算符找到输入
【发布时间】:2015-02-19 05:54:24
【问题描述】:

我目前正在做一些作业,我将两个文本文件加载到每个包含 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()

【问题讨论】:

  • 根据您的描述,这不太可能是您的问题,但请注意 Python 切片 [a:b] 返回索引为 a 的元素,包括 b-1,而不是 b .

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


【解决方案1】:

问题出在这两行:

boyList = [readBoyNames]
girlList = [readGirlNames]

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

boyList= readBoyNames
girlList= readGirlNames

它没有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2019-07-10
    • 2013-07-24
    • 2023-01-13
    • 2012-05-15
    相关资源
    最近更新 更多