使用通配符搜索元组列表?

1 投票
6 回答
14431 浏览
提问于 2025-04-16 09:12

我该如何在一个包含多个元组的列表中搜索,如果我只知道其中一个元组的某个元素呢?

举个例子(这个例子是错误的):

tuplelist = [('cat', 'dog'), ('hello', 'goodbye'), ('pretty', 'ugly')]
matchlist = []
searchstring = 'goodbye'

if (*, searchstring) in tuplelist:
    print "match was found"
    matchlist.append(tuplelist[#index of match])

星号(*)是我想放置通配符的地方。

我知道我可以使用:

for i in range (len(tuplelist)):
    if tuplelist[i][1]==searchstring:
        matchlist.append(tuplelist[i])
        print "match was found"

但问题是,如果没有找到匹配项,我需要只运行一个特定的函数一次。

也许我可以做一个计数器,当找到匹配时就加一,然后在循环中加上类似这样的东西。

    if i==len(tuplelist) and matchcounter==0:
        #do something
        print "no match was found"

但我觉得这样有点麻烦和混乱,我相信还有更简单的方法可以做到这一点 :P

6 个回答

4

觉得你想要做的是部分有序匹配;下面的代码使用None作为通配符:

def tupleMatch(a,b):
    return len(a)==len(b) and all(i is None or j is None or i==j for i,j in zip(a,b))

def tupleCombine(a,b):
    return tuple([i is None and j or i for i,j in zip(a,b)])

def tupleSearch(findme, haystack):
    return [tupleCombine(findme,h) for h in haystack if tupleMatch(findme, h)]

findme = (None, "goodbye")
haystack = [
    ('cat', 'dog'),
    ('hello', 'goodbye'),
    ('pretty', 'ugly'),
    ('tomorrow', 'goodbye'),
    ('goodbye', 'today'),
    ('anything', None)
]
tupleSearch(findme, haystack)

返回结果是

[('hello', 'goodbye'), ('tomorrow', 'goodbye'), ('anything', 'goodbye')]
7

我很惊讶居然没有人提到这一点,这个问题其实已经存在很久了,但我还是想把它放在这里,以防有人像我一样碰到。

在Python中,有一个叫做for...else的结构,正好可以用来解决这个问题。你可以这样做(我会用Mark Byers的代码并稍作修改):

for t in tuplelist:
    if t[1] == searchstring:
        #do something
        print "match was found"
        break
else:
    print "not matches found"
    # call function if not matches were found.

else部分只有在循环正常结束时才会执行,也就是说没有遇到break。

5

你可以这样做:

found_match = False

for t in tuplelist:
    if t[1] == searchstring:
        #do something
        print "match was found"
        found_match = True

if not found_match:
    # ...

撰写回答