如果我只知道列表中任何元组的 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])
星号将是我要放置通配符的地方
我知道我可以使用:
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
请您参考如下方法:
令我惊讶的是,还没有人真正指出这一点,这是一个相当古老的问题,但我会把它留在这里,以防有人像我一样偶然发现这个问题。
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 部分只有在循环正常退出(没有中断)时才会发生。
