[英]Python: fastest way to define a function using a list of 2-tuples
Suppose L is a list of two tuples, with len(L)~16,000
. 假设L是两个元组的列表,其中len(L)~16,000
。
An element of L
is of the form (x,y) where in my case x is itself a list of 7 elements and y is a float. L
的元素形式为(x,y),在我的情况下,x本身是7个元素的列表,而y是浮点数。
How can I define a function f such that it computes f(x)=y using L
? 如何定义函数f,使其使用L
计算f(x)= y? Right now I am using the naive code: 现在我正在使用朴素的代码:
def f(x):
for i in range(0,len(L)):
if x==L[i][0]:
return L[i][1]
But this is taking way too long. 但这花费的时间太长了。 Any suggestions to make this run faster? 有什么建议可以加快运行速度吗?
tabulate = dict(L)
f = tabulate.get
This will work as long as you use tuples for your keys instead of lists. 只要您将元组用作键而不是列表,这将起作用。
What you're implementing is called an association list, for example: 您要实现的称为关联列表,例如:
L = [ ('x', 1), ('y', 2), ('z', 3) ]
A far better data structure to use in Python would be a dictionary: 在Python中使用更好的数据结构是字典:
D = { 'x':1, 'y':2, 'z':3 }
Look, you can even transform an association list into a dictionary: 看,您甚至可以将关联列表转换成字典:
D = dict(L)
Now you can quickly retrieve any value from it: 现在,您可以从中快速检索任何值:
D['y']
=> 2
Try using a dict, a list of key-value pairs that you can use to do lookups, it would be perfect for your "function" 尝试使用字典,即可以用于查找的键值对列表,这对您的“功能”非常理想
Here is an overview of the python dict datatype: 这是python dict数据类型的概述:
http://www.tutorialspoint.com/python/python_dictionary.htm http://www.tutorialspoint.com/python/python_dictionary.htm
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.