在列表中查找以指定用户开头的项

2024-10-03 13:31:11 发布

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

我正在尝试做一个程序,其中我已经有一个列表,正在从一个.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.

这是我最初的想法,但它没有起作用,我不知道该怎么做。。在


Tags: thetxtinputifislineprintplease
2条回答

假设您已经准备好文本中的列表,则可以使用用户输入和列表将其调用到此函数:

def startString(char, userlist):
    ls = []
    for string in userlist:
        if string.startswith(char):
            ls.append(string)
    print(ls)

startString(userI,yourList) #call fuction on your data(userinput and your list from text)

您可以使用列表理解来执行以下操作:

text = open('data.txt').read()
user_letter = raw_input('Please enter one letter: ')
starts_with = [word for word in text.split() if word.startswith(user_letter)]

相关问题 更多 >