Python 快速迭代元组列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16021571/
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
iterating quickly through list of tuples
提问by memyself
I wonder whether there's a quicker and less time consuming way to iterate over a list of tuples, finding the right match. What I do is:
我想知道是否有一种更快、更省时的方法来迭代元组列表,找到正确的匹配项。我要做的是:
# this is a very long list.
my_list = [ (old1, new1), (old2, new2), (old3, new3), ... (oldN, newN)]
# go through entire list and look for match
for j in my_list:
if j[0] == VALUE:
PAIR_FOUND = True
MATCHING_VALUE = j[1]
break
this code can take quite some time to execute, depending on the number of items in the list. I'm sure there's a better way of doing this.
执行此代码可能需要相当长的时间,具体取决于列表中的项目数。我相信有更好的方法来做到这一点。
采纳答案by Sanjay T. Sharma
Assuming a bit more memory usage is not a problem and if the first item of your tuple is hashable, you can create a dictout of your list of tuples and then looking up the value is as simple as looking up a key from the dict. Something like:
假设更多的内存使用不是问题,并且如果您的元组的第一项是可散列的,您可以从您的元组列表中创建一个dict,然后查找该值就像从dict. 就像是:
dct = dict(tuples)
val = dct.get(key) # None if item not found else the corresponding value
EDIT: To create a reverse mapping, use something like:
编辑:要创建反向映射,请使用以下内容:
revDct = dict((val, key) for (key, val) in tuples)
回答by Eric
I think that you can use
我认为你可以使用
for j,k in my_list:
[ ... stuff ... ]
回答by tom
The code can be cleaned up, but if you are using a list to store your tuples, any such lookup will be O(N).
可以清理代码,但是如果您使用列表来存储元组,则任何此类查找都将是 O(N)。
If lookup speed is important, you should use a dictto store your tuples. The key should be the 0th element of your tuples, since that's what you're searching on. You can easily create a dict from your list:
如果查找速度很重要,您应该使用 adict来存储您的元组。键应该是元组的第 0 个元素,因为这就是您要搜索的元素。您可以轻松地从列表中创建一个字典:
my_dict = dict(my_list)
Then, (VALUE, my_dict[VALUE])will give you your matching tuple (assuming VALUEexists).
然后,(VALUE, my_dict[VALUE])会给你匹配的元组(假设VALUE存在)。
回答by Peter Tsung
I wonder whether the below method is what you want.
我想知道下面的方法是否是你想要的。
You can use defaultdict.
您可以使用defaultdict.
>>> from collections import defaultdict
>>> s = [('red',1), ('blue',2), ('red',3), ('blue',4), ('red',1), ('blue',4)]
>>> d = defaultdict(list)
>>> for k, v in s:
d[k].append(v)
>>> sorted(d.items())
[('blue', [2, 4, 4]), ('red', [1, 3, 1])]
回答by Vaibhav Singh
The question is dead but still knowing one more way doesn't hurt:
这个问题已经死了,但仍然知道另一种方式不会伤害:
my_list = [ (old1, new1), (old2, new2), (old3, new3), ... (oldN, newN)]
for first,*args in my_list:
if first == Value:
PAIR_FOUND = True
MATCHING_VALUE = args
break

