Python 中的嵌套 for 循环与 map 函数的比较
我正在 python 中工作,目前有以下代码:
list = []
for a in range(100):
for b in range(100):
for c in range(100):
list.append(run(a,b,c))
其中 run(a,b,c) 返回一个整数(例如,它可以将三个数字相乘)。有没有更快的方法来循环这些数字或使用地图函数?
谢谢 :)
I'm working in python and currently have the following code:
list = []
for a in range(100):
for b in range(100):
for c in range(100):
list.append(run(a,b,c))
where run(a,b,c) returns an integer (for example, it could multiply the three numbers together). Is there a faster way to either loop over these numbers or use a map function?
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
看看itertools-module,特别是product 方法
示例用法:
函数调用可以缩短为:
请注意,示例中的 多于。有关解包参数列表的说明,请参阅 docs.python.org。
例如,
product(range(0,2), Repeat=3))
的输出如下所示:Have a look at the itertools-module and particulary the product method
example usage:
Note that the function call can be shortened to:
in the example above. see docs.python.org for explanation of Unpacking Argument Lists.
As an example, the output from
product(range(0,2), repeat=3))
looks like this:我认为你可以使用 imap 来执行此操作:
imap 产生其结果...所以如果你想迭代结果,请不要使用 list()
I think you can use imap to do this :
imap yields its result... so if you want to iterate of the results don't use the list()
或者:
Or:
另一种选择,具体取决于您想要做什么:
当然,这一切都取决于
run
,例如,如果您想获取产品,您也可以对整个数组进行操作,这要快得多:an alternative, depending on what you want to do exactly:
Of course, it all depends on
run
, e.g. if you want to take the product, you could also operate on the whole array, which is much faster: