2013-03-18 121 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