4

好的,我有这个代码:

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

search = str(raw_input())

found = "not"

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

到目前为止,只有当您在终端中键入与列表中完全相同的字符串时,它才能在列表中找到一项,这就是问题所在。

我需要能够在终端中键入一个或两个字符并拥有它,以便它列出列表中与搜索匹配的字符串(例如:如果我要在终端中键入“P”,它将列出“Pink " 和 "Purple" 因为到目前为止它们与我的搜索匹配,但不完全匹配)

我可能忽略了一些东西,但是,有没有一种方法可以让我以这种方式搜索一个列表,而不必有超过 200 行代码(200 多行,因为我需要实现它以在列表中有超过 150 个字符串)只是为了搜索为字符串?

4

7 回答 7

5

最简单的方法,使用列表推导:

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

如果你有一个很大的列表,这可能不会那么好。

于 2013-03-18T01:17:01.377 回答
2

你需要的是一个合适的数据结构。从您的需求描述来看,我认为trie就是其中之一。

您使用颜色列表构建一个 trie,然后使用用户输入搜索 trie(允许使用前缀)。您可以在github上找到各种实现或自己实现。:)

于 2013-03-18T01:18:17.097 回答
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"

否则,使用 Trie:http ://en.wikipedia.org/wiki/Trie

于 2013-03-18T01:19:00.843 回答
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 及以上的比率。

于 2013-03-18T01:25:46.947 回答
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
于 2013-03-18T01:27:29.783 回答
1
search = str(raw_input())

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

然后循环匹配并打印。

于 2013-03-18T01:16:56.117 回答
1
    for c in colors:
        if c[0:len(search)-1] == search:
            print "Found!"

不是绝对最优雅的解决方案,但它可以完成工作。只需遍历列表并比较相关的子字符串。诚然,如果搜索字符串比颜色中的任何元素长,您可能希望将其包装在 KeyError 的 try/catch 块中。

于 2013-03-18T01:17:22.710 回答