[英]Searching a List of Lists - Python
基本上,我已經將制表符分隔的txt文件轉換為包含每本書(書名,作者,出版商等)的一堆列表的列表,並且我想出了如何使用索引進行搜索的方法,但是我如何做到這一點搜索並返回甚至部分匹配的任何內容。
import csv
import itertools
list_of_books = list(csv.reader(open('bestsellers.txt','rb'), delimiter='\t'))
search = 'Tom Clancy'
for sublist in list_of_books:
if sublist[1] == search:
print sublist
例如。 因此,無需搜索“湯姆·克蘭西”就可以輸入“克蘭西”,並且仍然可以獲取湯姆·克蘭西的所有小說。
謝謝。
我認為這可以滿足您的需求:
search = 'Tom Clancy'
for sublist in list_of_books:
if search in sublist[1]:
print sublist
更新:
我想您也希望將兩個字符串都轉換為小寫,如下所示:
if search.lower() in sublist[1].lower():
這取決於你的意思是部分到底是什么了一下。
第一個定義: search
詞應完全匹配,但可以在字符串中的任意點匹配。 這可能幾乎就是您的意思。 在這種情況下,您確實要檢查子列表是否包含搜索詞。 為此,您想使用Python的in
運算符:
if search in sublist[1]:
print sublist
由於均等與包含之間的差異,因此速度會稍慢甚至非常慢。 我懷疑這對您很重要。
第二個定義:與第一個定義相同,但大小寫無關緊要。 在這種情況下,您想規范大小寫,基本上只需使用Python的lower
(或upper
)字符串方法,使大寫或小寫都相同就可以忽略它們。
search = 'Tom Clancy'
search_lower = search.lower() # move the search lowering
for sublist in list_of_books:
# since strings are immutable, sublist[1].lower() creates a new lower-cased
# string to be compared against search_lower. sublist[1] doesn't get modified
if search_lower in sublist[1].lower():
print sublist
那可能就是你想要的。
第三個定義是“模糊匹配”。 如果您接受模糊匹配,則clincy
可能匹配Clancy
。 哎呀,如果搜索模糊,那么tom
可以匹配Clancy
。 這就是蠕蟲的全部“零食”。 幸運的是, 這個Stack Overflow問題中有一堆庫可以提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.