【发布时间】: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