用通配符搜索元组列表?

Ste*_*son 1 python tuples list

如果我只知道列表中任何元组的1个元素,我该如何搜索元组列表?

模型示例(这不起作用):

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

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

asterix将是我想放置通配符的地方

我知道我可以使用:

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

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

也许我可以制作一个在找到匹配时递增的计数器,并将这样的东西添加到循环中.

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

但是我认为那种丑陋和混乱,我确信有一些更清洁的方法可以做到这一点:P

Far*_*ori 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.
Run Code Online (Sandbox Code Playgroud)

只有当循环正常退出(没有中断)时才会发生else部分.


Mar*_*ers 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:
    # ...
Run Code Online (Sandbox Code Playgroud)

  • 请注意,另一种说法是:any(t[1] == searchstring for t in tuplelist) (4认同)