在列表列表中进行Python搜索 [英] Python search in lists of lists
问题描述
我有一个包含两个项目的列表,需要在其中进行搜索.
I have a list of two-item lists and need to search for things in it.
如果列表为:
list =[ ['a','b'], ['a','c'], ['b','d'] ]
我可以轻松地搜索一对
['a','b'] in list
现在,有没有办法查看我是否有一对仅在第二个位置存在一个字符串?我可以这样做:
Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:
for i in range (0, len(list)):
if list[i][1]==search:
found=1
但是没有for
循环,有没有(更好的)方法呢?我不需要知道i
或在找到它之后就让循环继续进行.
But is there a (better) way without the for
loop? I don't need to know i
or keep the loop going after it's found.
推荐答案
您总是会有一个循环-有人可能会带一个聪明的单线,将循环隐藏在对map()
或类似内容的调用中,但总会在那里.
You're always going to have a loop - someone might come along with a clever one-liner that hides the loop within a call to map()
or similar, but it's always going to be there.
除非性能是主要因素,否则我总是倾向于使用简洁简洁的代码.
My preference would always be to have clean and simple code, unless performance is a major factor.
这里可能是代码的Python版本:
Here's perhaps a more Pythonic version of your code:
data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
for sublist in data:
if sublist[1] == search:
print "Found it!", sublist
break
# Prints: Found it! ['a', 'c']
一旦找到匹配项,它就会跳出循环.
It breaks out of the loop as soon as it finds a match.
(顺便说一下,您在['b''d']
中有一个错字.)
(You have a typo, by the way, in ['b''d']
.)
这篇关于在列表列表中进行Python搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!