创建列表的多个副本的最快方法 [英] Fastest way to create multiple copies of a list
问题描述
我正在为我的迷宫求解器开发一种广度优先的搜索算法,到目前为止,它一直在工作.我通过复制前一个堆栈并将当前值附加到当前堆栈来跟踪当前堆栈.
I am working on a breadth-first search algorithm for my maze solver and it is working so far. I am keeping track of the current stack by copying the previous one and appending the current value to it.
由于复制列表需要花费大量时间,因此我想在一次操作中创建列表的多个副本.
Since copying list takes a great amount of time I would like to create multiple copies of the list within one operation.
-
复制列表并将其分配给多个变量.
Copy the list and assign it to multiple variables.
l = [1, 2, 3]
a = b = c = l[:] # Just creates references and no individual lists
使用具有copy
函数(比list[:]
更快)的numpy数组.
Use numpy arrays with copy
function (faster than list[:]
).
创建一个列表的多个副本的最快方法是什么?
What is the fastest way to create multiple copies of one list?
推荐答案
请勿在堆栈中使用普通的Python列表.使用Lisp样式的链表,因此您的堆栈彼此共享其大部分结构,并且使用额外的元素构建新堆栈的时间是恒定的:
Don't use ordinary Python lists for your stacks. Use Lisp-style linked lists, so your stacks share most of their structure with each other and building a new stack with an additional element is constant time:
def empty_stack():
return ()
def push(stack, item):
return (item, stack)
def stack_to_list(stack):
l = []
while stack:
item, stack = stack
l.append(item)
return l[::-1]
在这里,push
以恒定的时间运行并生成新的堆栈,而不会改变旧堆栈,因此您可以在旧堆栈上重复调用push
而不复制它.
Here, push
runs in constant time and produces a new stack, without mutating the old, so you can call push
on the old stack repeatedly without copying it.
这篇关于创建列表的多个副本的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!