如何在 Python 中获取任意大小的空列表?

发布于 2024-10-20 14:39:48 字数 244 浏览 6 评论 0原文

我基本上想要一个与 C: 中的这个数组等效的 Python,

int a[x];

但在 python 中我声明了一个像这样的数组:

a = []

问题是我想用像这样的值分配随机槽:

a[4] = 1

但我不能用 Python 做到这一点,因为 Python 列表是空(长度为 0)。

I basically want a Python equivalent of this Array in C:

int a[x];

but in python I declare an array like:

a = []

and the problem is I want to assign random slots with values like:

a[4] = 1

but I can't do that with Python, since the Python list is empty (of length 0).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

古镇旧梦 2024-10-27 14:39:48

如果“数组”实际上是指 Python 列表,则可以使用

a = [0] * 10

a = [None] * 10

If by "array" you actually mean a Python list, you can use

a = [0] * 10

or

a = [None] * 10
↘人皮目录ツ 2024-10-27 14:39:48

你不能在Python中完全做你想做的事(如果我没理解错的话)。您需要为列表(或如您所说的数组)的每个元素添加值。

但是,尝试一下:

a = [0 for x in range(N)]  # N = size of list you want
a[i] = 5  # as long as i < N, you're okay

对于其他类型的列表,请使用 0 以外的值。None 通常也是一个不错的选择。

You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).

But, try this:

a = [0 for x in range(N)]  # N = size of list you want
a[i] = 5  # as long as i < N, you're okay

For lists of other types, use something besides 0. None is often a good choice as well.

帅的被狗咬 2024-10-27 14:39:48

您可以使用 numpy:

import numpy as np

空数组中的示例:

np.empty([2, 2])
array([[ -9.74499359e+001,   6.69583040e-309],
       [  2.13182611e-314,   3.06959433e-309]])  

You can use numpy:

import numpy as np

Example from Empty Array:

np.empty([2, 2])
array([[ -9.74499359e+001,   6.69583040e-309],
       [  2.13182611e-314,   3.06959433e-309]])  
愚人国度 2024-10-27 14:39:48

您也可以使用列表的扩展方法来扩展它。

a= []
a.extend([None]*10)
a.extend([None]*20)

also you can extend that with extend method of list.

a= []
a.extend([None]*10)
a.extend([None]*20)
木格 2024-10-27 14:39:48

只需声明列表并附加每个元素即可。例如:

a = []
a.append('first item')
a.append('second item')

Just declare the list and append each element. For ex:

a = []
a.append('first item')
a.append('second item')
倒带 2024-10-27 14:39:48

如果您(或此问题的其他搜索者)实际上有兴趣创建一个连续数组来填充整数,请考虑 bytearraymemoryivew

# cast() is available starting Python 3.3
size = 10**6 
ints = memoryview(bytearray(size)).cast('i') 

ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))

ints[0]
# 0

ints[0] = 16
ints[0]
# 16

If you (or other searchers of this question) were actually interested in creating a contiguous array to fill with integers, consider bytearray and memoryivew:

# cast() is available starting Python 3.3
size = 10**6 
ints = memoryview(bytearray(size)).cast('i') 

ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))

ints[0]
# 0

ints[0] = 16
ints[0]
# 16
留一抹残留的笑 2024-10-27 14:39:48

还可以创建一个具有特定大小的空数组:

array = [[] for _ in range(n)] # n equal to your desired size
array[0].append(5) # it appends 5 to an empty list, then array[0] is [5]

如果将其定义为 array = [] * n 那么如果您修改一项,由于其可变性,所有项都会以相同的方式更改。

It is also possible to create an empty array with a certain size:

array = [[] for _ in range(n)] # n equal to your desired size
array[0].append(5) # it appends 5 to an empty list, then array[0] is [5]

if you define it as array = [] * n then if you modify one item, all are changed the same way, because of its mutability.

眼睛会笑 2024-10-27 14:39:48
x=[]
for i in range(0,5):
    x.append(i)
    print(x[i])
x=[]
for i in range(0,5):
    x.append(i)
    print(x[i])
魂归处 2024-10-27 14:39:48

如果你确实想要一个 C 风格的数组,

import array
a = array.array('i', x * [0])
a[3] = 5
try:
   [5] = 'a'
except TypeError:
   print('integers only allowed')

请注意,Python 中没有未初始化变量的概念。变量是绑定到值的名称,因此该值必须具有某些内容。在上面的示例中,数组用零初始化。

然而,这在 python 中并不常见,除非你确实需要它来处理低级的东西。在大多数情况下,正如其他答案所建议的那样,最好使用空列表或空 numpy 数组。

If you actually want a C-style array

import array
a = array.array('i', x * [0])
a[3] = 5
try:
   [5] = 'a'
except TypeError:
   print('integers only allowed')

Note that there's no concept of un-initialized variable in python. A variable is a name that is bound to a value, so that value must have something. In the example above the array is initialized with zeros.

However, this is uncommon in python, unless you actually need it for low-level stuff. In most cases, you are better-off using an empty list or empty numpy array, as other answers suggest.

悟红尘 2024-10-27 14:39:48

分配“随机槽”的(我认为唯一的)方法是使用字典,例如:

 a = {}     # initialize empty dictionary
 a[4] = 1   # define the entry for index 4 to be equal to 1
 a['French','red'] = 'rouge'  # the entry for index (French,red) is "rouge".

这对于“快速破解”来说很方便,并且如果您没有对数组元素的密集访问,则查找开销是无关紧要的。
否则,使用固定大小的预分配(例如 numpy)数组会更有效,您可以使用 a = np.empty(10) 创建该数组(对于未初始化的向量长度为 10) 或 a = np.zeros([5,5])(对于用零初始化的 5x5 矩阵)。

备注:在您的 C 示例中,您还必须在分配(不是这样)“随机槽”(即 0 和 x 之间的整数索引)之前分配数组(您的 int a[x];) -1)。

参考资料:

The (I think only) way to assign "random slots" is to use a dictionary, e.g.:

 a = {}     # initialize empty dictionary
 a[4] = 1   # define the entry for index 4 to be equal to 1
 a['French','red'] = 'rouge'  # the entry for index (French,red) is "rouge".

This can be handy for "quick hacks", and the lookup overhead is irrelevant if you don't have intensive access to the array's elements.
Otherwise, it will be more efficient to work with pre-allocated (e.g., numpy) arrays of fixed size, which you can create with a = np.empty(10) (for an non-initialized vector of length 10) or a = np.zeros([5,5]) for a 5x5 matrix initialized with zeros).

Remark: in your C example, you also have to allocate the array (your int a[x];) before assigning a (not so) "random slot" (namely, integer index between 0 and x-1).

References:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文