如何拆分列表中的多个字符串?

2024-05-19 12:03:44 发布

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

问题的背景是我想为电影列表创建一个搜索引擎。你知道吗

movies_list=["Avatar", "Planet of the Apes", "Rise of the Apes", "Avatar the Second"]

因此,我希望用户能够搜索,例如,Apes,程序将显示

Planet of the Apes
Rise of the Apes

我想尝试但我知道行不通的代码是

movieSearch = movies_list.split()
search = input(str("Search: ")

for movie in movies_list
     if(movieSearch == search):
          print(movie)
     if(movieSearch != search): 
          print("No Match")

主要是因为我知道movieSearch行不通,但我只是不知道还能做什么


Tags: ofthesearchif电影moviesmovielist
3条回答

试试这个:

print('\n'.join(x for x in movies_list if search in x) or 'No results')

请这样做:

flag=0
search = str(input("Search: "))
for movie in movies_list:
    if search in movie:
        flag=1
        print(movie)
if not flag:
    print("no match") 

脓道:

movies_list=["Avatar", "Planet of the Apes", "Rise of the Apes", "Avatar the Second"]
def match_movie(name):
    return [movie for movie in movies_list if name in movie] or 'No Match'

您可以简单地使用以下内容:

>>> search = "Apes"
>>> [i for i in movies_list if search in i.split()]
['Planet of the Apes', 'Rise of the Apes']

请注意,这将只搜索准确的单词,并且区分大小写。例如,如果search = "apes"search = "APES",那么上面的代码只会生成一个空列表。你知道吗

要使其成为不区分大小写的搜索,可以使用^{}(或^{})将字符串转换为其中一个大小写,然后进行比较。你知道吗

# Convert the `movies_list` to lower case
>>> movies_list = [i.lower() for i in movies_list]

# Convert `search` to lower case and then compare
>>> [i for i in movies_list if search.lower() in i.split()]

编辑:i.split()将给出准确的单词搜索结果。如果您想要部分搜索,那么只需使用i。你知道吗

[i for i in movies_list if search in i]

相关问题 更多 >

    热门问题