如何在python中创建固定大小列表? [英] How to create a fix size list in python?

查看:1155
本文介绍了如何在python中创建固定大小列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我可以创建一个类似于...的数组

In C++, I can create a array like...

int* a = new int[10];

在python中,我只知道我可以声明一个列表,而不是附加一些项目,或类似..

in python,I just know that I can declare a list,than append some items,or like..

l = [1,2,3,4]
l = range(10)

我可以按照给定的大小初始化列表,例如c ++,并且不进行任何赋值吗?

Can I initialize a list by a given size,like c++,and do not do any assignment?

推荐答案

(tl; dr:您问题的确切答案是numpy.emptynumpy.empty_like,但您可能不在乎,可以摆脱使用myList = [None]*10000.)

(tl;dr: The exact answer to your question is numpy.empty or numpy.empty_like, but you likely don't care and can get away with using myList = [None]*10000.)

您可以将列表初始化为所有相同的元素.使用非数字值在语义上有意义(如果使用它会在以后产生错误,这是一件好事)还是类似0(不寻常?如果您正在编写稀疏矩阵或'默认值应为0,并且您不必担心错误)由您自己决定:

You can initialize your list to all the same element. Whether it semantically makes sense to use a non-numeric value (that will give an error later if you use it, which is a good thing) or something like 0 (unusual? maybe useful if you're writing a sparse matrix or the 'default' value should be 0 and you're not worried about bugs) is up to you:

>>> [None for _ in range(10)]
[None, None, None, None, None, None, None, None, None, None]

(这里_只是一个变量名,您可能使用过i.)

(Here _ is just a variable name, you could have used i.)

您也可以这样:

>>> [None]*10
[None, None, None, None, None, None, None, None, None, None]

您可能不需要优化它.您还可以在每次需要时追加到数组:

You probably don't need to optimize this. You can also append to the array every time you need to:

>>> x = []
>>> for i in range(10):
>>>    x.append(i)


简单方法的性能比较

哪个最好?


Performance comparison of simple methods

Which is best?

>>> def initAndWrite_test():
...  x = [None]*10000
...  for i in range(10000):
...   x[i] = i
... 
>>> def initAndWrite2_test():
...  x = [None for _ in range(10000)]
...  for i in range(10000):
...   x[i] = i
... 
>>> def appendWrite_test():
...  x = []
...  for i in range(10000):
...   x.append(i)

python2.7中的结果:

Results in python2.7:

>>> import timeit
>>> for f in [initAndWrite_test, initAndWrite2_test, appendWrite_test]:
...  print('{} takes {} usec/loop'.format(f.__name__, timeit.timeit(f, number=1000)*1000))
... 
initAndWrite_test takes 714.596033096 usec/loop
initAndWrite2_test takes 981.526136398 usec/loop
appendWrite_test takes 908.597946167 usec/loop

python 3.2的结果:

Results in python 3.2:

initAndWrite_test takes 641.3581371307373 usec/loop
initAndWrite2_test takes 1033.6499214172363 usec/loop
appendWrite_test takes 895.9040641784668 usec/loop

如我们所见,最好在python2和python3中都使用成语[None]*10000.但是,如果执行的工作比分配还要复杂(例如,要生成或处理列表中的每个元素都比较复杂),那么开销将占成本的一小部分.也就是说,如果您对列表元素做任何合理的事情,这种优化还为时过早.

As we can see, it is likely better to do the idiom [None]*10000 in both python2 and python3. However, if one is doing anything more complicated than assignment (such as anything complicated to generate or process every element in the list), then the overhead becomes a meaninglessly small fraction of the cost. That is, such optimization is premature to worry about if you're doing anything reasonable with the elements of your list.

这些都是效率低下的,因为它们要经过内存,在过程中写一些东西.在C语言中,情况有所不同:未初始化的数组填充有随机垃圾存储器(注:已从系统重新分配,并且可以是安全风险(在您关闭程序时分配内存或无法锁死和/或无法删除内存).这是一个旨在提高速度的设计选择:C语言的开发人员认为最好不要自动初始化内存,这是正确的选择.

These are all however inefficient because they go through memory, writing something in the process. In C this is different: an uninitialized array is filled with random garbage memory (sidenote: that has been reallocated from the system, and can be a security risk when you allocate or fail to mlock and/or fail to delete memory when closing the program). This is a design choice, designed for speedup: the makers of the C language thought that it was better not to automatically initialize memory, and that was the correct choice.

这不是渐进式加速(因为它是O(N)),但是例如,在用实际关心的内容覆盖之前,您不需要先初始化整个内存块.如果可能的话,这等效于(伪代码)x = list(size=10000).

This is not an asymptotic speedup (because it's O(N)), but for example you wouldn't need to first initialize your entire memory block before you overwrite with stuff you actually care about. This, if it were possible, is equivalent to something like (pseudo-code) x = list(size=10000).

如果要在python中使用类似的东西,可以使用numpy数字矩阵/N维数组操作包.具体来说, numpy.empty numpy.empty_like

If you want something similar in python, you can use the numpy numerical matrix/N-dimensional-array manipulation package. Specifically, numpy.empty or numpy.empty_like

那是您问题的真正答案.

That is the real answer to your question.

这篇关于如何在python中创建固定大小列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆