我正在尝试做一个程序,其中我已经有一个列表,正在从一个.txt文件中读取,现在我需要做它,以便当我给Python我的“期望的字母”时,它将把我所有以该字母开头的项目放入另一个列表中。在
提前谢谢
countrypopList = open("E:\\SCRIPTING\\Countries.txt").readlines() #This is making "countrypopList" contain everthing on the txt.
countrypopList.sort() #This is sorting the list alphabetically.
useriList = []
countries = []
population = []
userI = input("Please input a single letter: ") #Ask user to input a single letter.
if userI.isalpha():
if len(userI) > 1:
print("Please enter only a single letter.") #If user input length is over 1, display this message.
else: #If there are no complications and the user inputs a single letter as required, the program continues.
#print("continue")
for line in countrypopList:
if (line.startswith(userI)):
useriList.append(line)
print(useriList)
else:
print("Please make sure that you enter a single letter.") #If user inputs anything other than a letter with a length of 1, display this message.
这是我最初的想法,但它没有起作用,我不知道该怎么做。。在
假设您已经准备好文本中的列表,则可以使用用户输入和列表将其调用到此函数:
您可以使用列表理解来执行以下操作:
相关问题 更多 >
编程相关推荐