在列表列表中搜索字符串

时间:2018-10-28 20:03:22

标签: python search

我一直在尝试向代码中添加一个功能,该功能允许用户在列表中搜索某些关键字。仅当输入与元素相同但我希望包含输入的每个元素都显示时,它才起作用。

infil = open("books.txt" , "r")
books_string = infil.read()
infil.close()
books_li = books_string.splitlines()
books_li.sort()

li_to_present= []
for element in books_li:
    parts = element.split(",")
    li_to_present.append(parts)

user_in = input("Search: ")
matches = [x for x in li_to_present if user_in in x]

示例: 列表li_to_present的一部分是:

['Birgitta Trotzig', ' Dykungens dotter'], ['Bo Giertz', ' Stengrunden']

如果用户输入的是"Birgitta",则不会添加到新列表匹配项中

有人可以很好地解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

import re

infil = open("books.txt" , "r")
books_string = infil.read()
infil.close()
books_li = books_string.splitlines()
books_li.sort()


li_to_present = []
for element in books_li:
    parts = element.split(",")
    li_to_present.append(parts)

user_in = input("Search: ")
matches = [x for x in li_to_present if re.search(user_in, x)]

答案 1 :(得分:0)

在生成器上使用all()函数,该函数将生成用户输入是否在子列表的每个字符串中。

user_in = input("Search: ")
matches = [l for l in li_to_present if any(user_in in s for s in l)]

例如

>>> li_to_present = [['Birgitta Trotzig', ' Dykungens dotter'],
                     ['Bo Giertz', ' Stengrunden']]
>>> user_in = input("Search: ")
Search: Birgitta
>>> matches = [l for l in li_to_present if any(user_in in s for s in l)]
>>> matches
[['Birgitta Trotzig', ' Dykungens dotter']]