2013-03-18 122 views
4

好吧,我有這樣的代碼:搜索Python列表

colors = ["Red" , "Green" , "Blue" , "Pink" , "Purple" , "Cyan"] 

search = str(raw_input()) 

found = "not" 

if search in colors: 
    print "Found!" 
else: 
    print "not Found" 

到目前爲止,它可以在列表中找到一個項目只有當你完全按照它在列表中的終端類型的字符串,也就是問題。

我需要能夠在終端中鍵入一個或兩個字符,並讓它列出列表中匹配搜索的字符串(例如:如果我要輸入「P」終端,它將列出「粉紅色」和「紫色」,因爲他們符合我的搜索,但不完全)

我可能會忽略一些東西,但是,有沒有一種方法可以搜索列表,而不必超過200行的代碼(200多行,因爲我需要實現這個在列表中有超過150個字符串)只是爲了搜索字符串?

+0

您是否在詢問Google的auto complete之類的「搜索建議」? – squiguy 2013-03-18 01:22:14

+0

@squiguy是啊,非常像 – 2013-03-18 01:28:26

回答

1
search = str(raw_input()) 

matches = [s for s in colors if s.startswith(search)] 

然後遍歷匹配並打印。

5

最簡單的方法,使用列表理解:

matches = [color for color in colors if color.startswith(search)] 

如果你有一個大名單,這可能不是如此上佳表現。

+1

會約200個字符串(每個可能15個字符)表現不佳嗎? – 2013-03-18 01:31:09

+0

@RogerParishIII:嘗試一下,看看它的表現如何。這是確保代碼運行速度的唯一方法。我只提到性能,因爲我認爲有更快的方法來做到這一點。 – 2013-03-18 01:38:35

+0

謝謝,這個作品完美! – 2013-03-18 02:00:51

1
for c in colors: 
     if c[0:len(search)-1] == search: 
      print "Found!" 

不是絕對最優雅的解決方案,但它可以完成工作。只需遍歷列表並比較相關的子字符串即可。無可否認,如果搜索字符串比任何顏色元素都長,您可能希望將其封裝在一個用於KeyError的try/catch塊中。

2

你需要的是一個合適的數據結構。根據您的要求描述,我認爲trie只是一個。

您使用顏色列表構建一個樹狀圖,然後使用用戶輸入(允許前綴)搜索樹狀圖。 你可以在github上找到不同的實現,或者自己實現它。 :)

2

如果性能是不是一個問題,(例如:顏色列表很小):

colors = ["Red" , "Green" , "Blue" , "Pink" , "Purple" , "Cyan"] 
search = str(raw_input()) 
found = "not" 

for color in colors: 
    # or if color.startswith(search), depend on your needs 
    if search in color: 
     print "Found" 

print "not Found" 

否則,使用特里:http://en.wikipedia.org/wiki/Trie

2

您可以使用difflib標準Python庫。

示例代碼:

from difflib import SequenceMatcher 
colors = ["Red", "Green", "Blue", "Pink", "Purple", "Cyan"] 
search = str(raw_input()) 
for color in colors: 
    s = SequenceMatcher(None, search, color) 

    if s.ratio() > 0.25: 
     print color 

輸出:

xxxx$ python foo.py 
p 
Purple 

注:

你可以操縱比賽比按您的需求。在這裏,我使用了0.25以上的挖掘模式比率。

2

使用正則表達式可以讓您確定有多少文本以及哪一部分需要匹配。以下將搜索字符串的開頭。

import re 

colors = ["Red" , "Green" , "Blue" , "Pink" , "Purple" , "Cyan"] 
search = re.compile("^"+str(raw_input())) 
isthere=[] 
for col in colors: 
    if search.findall(col)!=[]: 
     isthere.append(col) 

if isthere==[]: 
    print "Nothing there" 
else: 
    print isthere