如果我只知道列表中任何元组的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
最佳答案
您可以这样做:
found_match = False
for t in tuplelist:
if t[1] == searchstring:
#do something
print "match was found"
found_match = True
if not found_match:
# ...