簡體   English   中英

Python:在列表中搜索部分字符串

[英]Python: Search for partial string in a list

如果我有一個列表:

mylist = ['super mario brothers',
          'animal crossing',
          'legend of zelda breath of the wild',
          'kirby superstar ultra']

如果用戶輸入mario ,我可以star super mario brothers kirby superstar ultra legend of zelda breath of the wild zelda

將輸入作為ans

現在遍歷您的列表,對於列表中的每個句子,查看該句子是否包含ans ,如果是則打印該句子。

mylist = ['super mario brothers', 'animal crossing', 'legend of zelda breath of the wild', 'kirby superstar ultra']

ans = input('Enter name')

for title in mylist:
    if ans in title:
        print(title)

您可以使用in檢查一個字符串是否包含另一個字符串:

>>> 'mario' in 'super mario brothers'
True

所以:

given_name = 'mario'

for sentence in mylist:
    if given_name in sentence:
        print(sentence)

您可以使用in運算符。

我冒昧地通過小寫游戲名稱和用戶輸入來添加不區分大小寫。

list_of_games = [
    "Super Mario Brothers",
    "Animal Crossing",
    "Legend of Zelda Breath of the Wild",
    "Kirby Superstar Ultra",
]
search_string = input("Search for a game:").lower()
for title in list_of_games:
    if search_string in title.lower():
        print(title)

正如評論中所討論的那樣,如果您想根據與輸入匹配的游戲數量來處理不同的事情,我們可以改變事情,例如:

search_string = input("Search for a game:").lower()
# Build up a list of matching games using a list comprehension
matching_games = [title for title in list_of_games if search_string in title.lower()]
if not matching_games:  # the list is falsy if it's empty
    print("No matches for that input, sorry!")
elif len(matching_games) == 1:  # Only one match
    print("One match:", matching_games[0])
else:
    print("Multiple matches:")
    for title in matching_games:
        print("*", title)

或者,只是為了笑……這是一個單行:

[i if i.find('mario') > -1 else None for i in mylist][0]

本質上,這會檢查列表中的每個元素以查找搜索字符串,如果找到則返回第一個匹配的列表元素; 否則None返回。

您可以使用正則表達式,遍歷列表中的所有元素

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM