简体   繁体   中英

How to split multiple strings that are inside lists?

The context of the issue is me wanting to create a search engine for a list of movies.

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

So I want the user to be able to search, for example, Apes , and the program will display

Planet of the Apes
Rise of the Apes

The code I was thinking of trying but I know won't work was

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

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

Mainly because I know the movieSearch won't work but I'm just not sure on what else to do

Try this way:

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") 

Pythonic way:

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'

You could simply use something like this:

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

Do note that this will only search for the exact words and is case sensitive. For example if search = "apes" or search = "APES" , then the above code would simply generate an empty list.

To make it a case insensitive search you can use .lower() (or .upper() to convert the string into one of the cases and then compare them.

# 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()]

EDIT: i.split() will give an exact word search result. If you want a partial search then simply use i .

[i for i in movies_list if search in i]

You can do this in simple steps.

In [21]: movies_list=["Avatar", "Planet of the Apes", "Rise of the Apes", "Avatar the Second"]
In [25]: search = 'Apes'    
In [22]: [i for i in movies_list if search in i]
Out[22]: ['Planet of the Apes', 'Rise of the Apes']

尝试这个:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM