在 Python 中搜索二维元组/列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2205985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Searching a 2-Dimensional Tuple/List in Python
提问by Koobz
I want to search a tuple of tuples
for a particular string and return the index of the parent tuple. I seem to run into variations of this kind of search frequently.
我想搜索tuple of tuples
特定字符串并返回父元组的索引。我似乎经常遇到这种搜索的变体。
What is the most pythonic way to do this?
什么是最pythonic的方法来做到这一点?
I.E:
IE:
derp = (('Cat','Pet'),('Dog','Pet'),('Spock','Vulcan'))
i = None
for index, item in enumerate(derp):
if item[0] == 'Spock':
i = index
break
>>>print i
2
I could generalize this into a small utility function that takes an iterable, an index (I've hard coded 0
in the example) and a search value. It does the trick but I've got this notion that there's probably a one-liner for it ;)
我可以将其概括为一个小的实用程序函数,它接受一个可迭代对象、一个索引(我0
在示例中进行了硬编码)和一个搜索值。它可以解决问题,但我有一个想法,即它可能是单行的 ;)
I.E:
IE:
def pluck(iterable, key, value):
for index, item in enumerate(iterable):
if item[key] == value:
return index
return None
采纳答案by HS.
It does the trick but I've got this notion that there's probably a one-liner for it ;)
它可以解决问题,但我有一个想法,即它可能是单行的 ;)
The one-liner is probably notthe pythonic way to do it :)
one-liner 可能不是Pythonic 的方法:)
The method you have used looks fine.
您使用的方法看起来不错。
Edit:
编辑:
If you want to be cute:
如果你想变得可爱:
return next( (i for i,(k,v) in enumerate(items) if k=='Spock'),None)
next
takes a generator expression and returns the next value or the second argument (in this case None
) once the generator has been exhausted.
next
接受一个生成器表达式并None
在生成器耗尽后返回下一个值或第二个参数(在本例中为)。
回答by Siddharth Srivastava
Or you can do:
或者你可以这样做:
dict(derp)[<key_name>]
eg.
例如。
dict(derp)['Cat']
which will give you 'Pet'
这会给你“宠物”
回答by Siddharth Srivastava
If you're often searching the same tuple, you can build a dict.
如果您经常搜索同一个元组,则可以构建一个 dict。
lookup_table = dict((key, i) for i, (key, unused) in enumerate(derp))
print lookup_table['Spock']
--> 2
回答by Mr Shark
Another way of getting it in one line would be:
在一行中获取它的另一种方法是:
[d[0] for d in derp].index("Spock")
I'm not sure if the iterator evaluates all values before calling index, and therefor being inefficient.
我不确定迭代器是否在调用 index 之前评估所有值,因此效率低下。
回答by ron
Lambdas are fun!
Lambda 很有趣!
return reduce(
lambda x,(i,(a,b)): i,
filter(
lambda (i,(a,b)): a == "Spock",
enumerate(depr)
),
None
)