[英]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
Use numpy arrays with copy
function (faster than list[:]
). 使用具有
copy
功能的numpy数组(比list[:]
快)。
What is the fastest way to create multiple copies of one list? 创建一个列表的多个副本的最快方法是什么?
Don't use ordinary Python lists for your stacks. 不要为堆栈使用普通的Python列表。 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:
使用Lisp样式的链表,因此您的堆栈彼此共享大部分结构,并且使用额外的元素构建新堆栈的时间是恒定的:
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]
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. 在这里,
push
在固定时间运行,并产生一个新的堆栈,没有变异的历史,所以你可以调用push
反复对老堆栈不复制它。
You can just bulk copy it: 您可以批量复制它:
def copyList(thelist, number_of_copies):
return tuple(thelist[:] for _ in xrange(number_of_copies))
a, b, c = copyList(range(10), 3)
Here you have a live example 这里有一个现场例子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.