我目前正在做一些家庭作业,我在两个文本文件中加载了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()
问题在于这两条线:
readBoyNames
和readGirlNames
已经是列表。您正在创建一个包含另一个列表的列表。 如果你把这两行改成它工作没有问题。你知道吗
相关问题 更多 >
编程相关推荐