[英]Fastest Way to Multiply Dictionary Values and Output to 'list type'
I have two dictionaries with the same keys but different values. 我有两个具有相同键但不同值的词典。 I want to perform an operation that combines the two and then creates a 'list type' object of them in no specific order.
我想执行一个将两者结合起来的操作,然后按特定顺序创建它们的“列表类型”对象。 I am going to be doing this on large datasets so speed is a priority.
我将在大型数据集上执行此操作,因此速度是首要任务。 What is the fastest way of doing this?
这样做的最快方法是什么?
So far I have these ideas. 到目前为止,我有这些想法。 I am new to python so I don't know much about how each function operates but I am assuming option 2 is the fastest.
我是python的新手,所以我不太了解每个函数如何运行,但我假设选项2是最快的。 Are there faster methods?
有更快的方法吗?
mydict = {"cats":1,"dog":3,"bird":2,"wolves":10}
exp = {"cats":10,"dog":23,"bird":34,"wolves":43}
#Option 1
mydict.update((x, y**(exp[x])) for x, y in mydict.items())
items = mydict.values()
#Option 2 // I think this is currently the fastest
items = []
items.append(y**(exp[x]) for x,y in mydict.items())
#Option 3
items = numpy.array(len(mydict))
for x,y in mydict:
items[?] = y**(exp[x]) // Is there a way to do this? Maybe with a counter
How about 怎么样
[mydict[key]**exp[key] for key in mydict.keys()]
assuming mydict and exp both have the exact same keys? 假设mydict和exp都有完全相同的键?
Side note: 边注:
[mydict[key]**exp[key] for key in mydict]
does the same thing as above, the .keys()
is optional. 做与上面相同的事情,
.keys()
是可选的。
And if you're concerned with speed use the time module to test the speed of each method as such: 如果您关注速度,请使用时间模块来测试每种方法的速度:
import time
t = time.clock()
for i in range(1000):
# your code here, for example:
[mydict[key]**exp[key] for key in mydict.keys()]
print "time", time.clock() - t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.