如何在Python中声明数组?

问题:如何在Python中声明数组?

如何在Python中声明数组?

我在文档中找不到对数组的任何引用。

How do I declare an array in Python?

I can’t find any reference to arrays in the documentation.


回答 0

variable = []

现在variable引用一个空列表*

当然,这是分配,而不是声明。在Python中,没有办法说“此变量不应引用列表以外的任何东西”,因为Python是动态类型的。


*默认的内置Python类型称为list,而不是数组。它是一个任意长度的有序容器,可以容纳异构对象集合(它们的类型无关紧要,可以自由混合)。请勿将其与array模块混淆,后者提供的类型更接近C array类型。内容必须是同质的(所有类型都相同),但是长度仍然是动态的。

variable = []

Now variable refers to an empty list*.

Of course this is an assignment, not a declaration. There’s no way to say in Python “this variable should never refer to anything other than a list”, since Python is dynamically typed.


*The default built-in Python type is called a list, not an array. It is an ordered container of arbitrary length that can hold a heterogenous collection of objects (their types do not matter and can be freely mixed). This should not be confused with the array module, which offers a type closer to the C array type; the contents must be homogenous (all of the same type), but the length is still dynamic.


回答 1

这是Python中令人惊讶的复杂主题。

实用答案

数组由类表示list(请参见参考,不要将它们与generator混合使用)。

查看用法示例:

# empty array
arr = [] 

# init with values (can contain mixed types)
arr = [1, "eels"]

# get item by index (can be negative to access end of array)
arr = [1, 2, 3, 4, 5, 6]
arr[0]  # 1
arr[-1] # 6

# get length
length = len(arr)

# supports append and insert
arr.append(8)
arr.insert(6, 7)

理论答案

Python的list内幕是一个真实数组的包装,该数组包含对项目的引用。同样,基础数组会创建一些额外的空间。

其后果是:

  • 随机访问真的很便宜(arr[6653]与相同arr[0]
  • append 操作是“免费的”,同时有一些额外的空间
  • insert 操作费用昂贵

检查这张很棒的操作复杂性表

另外,请参见这张图片,在这里我试图显示数组,引用数组和链接列表之间的最重要区别:

This is surprisingly complex topic in Python.

Practical answer

Arrays are represented by class list (see reference and do not mix them with generators).

Check out usage examples:

# empty array
arr = [] 

# init with values (can contain mixed types)
arr = [1, "eels"]

# get item by index (can be negative to access end of array)
arr = [1, 2, 3, 4, 5, 6]
arr[0]  # 1
arr[-1] # 6

# get length
length = len(arr)

# supports append and insert
arr.append(8)
arr.insert(6, 7)

Theoretical answer

Under the hood Python’s list is a wrapper for a real array which contains references to items. Also, underlying array is created with some extra space.

Consequences of this are:

  • random access is really cheap (arr[6653] is same to arr[0])
  • append operation is ‘for free’ while some extra space
  • insert operation is expensive

Check this awesome table of operations complexity.

Also, please see this picture, where I’ve tried to show most important differences between array, array of references and linked list:


回答 2

您实际上并没有声明任何东西,但这是在Python中创建数组的方式:

from array import array
intarray = array('i')

有关更多信息,请参见数组模块:http : //docs.python.org/library/array.html

现在可能您不想要数组,而是列表,但是其他人已经回答了。:)

You don’t actually declare things, but this is how you create an array in Python:

from array import array
intarray = array('i')

For more info see the array module: http://docs.python.org/library/array.html

Now possible you don’t want an array, but a list, but others have answered that already. :)


回答 3

我认为您想要一个列表,其中前30个单元格已经填充。所以

   f = []

   for i in range(30):
       f.append(0)

斐波那契数列就是一个可以使用它的例子。请参阅欧拉计画中的问题2

I think you (meant)want an list with the first 30 cells already filled. So

   f = []

   for i in range(30):
       f.append(0)

An example to where this could be used is in Fibonacci sequence. See problem 2 in Project Euler


回答 4

这是这样的:

my_array = [1, 'rebecca', 'allard', 15]

This is how:

my_array = [1, 'rebecca', 'allard', 15]

回答 5

对于计算,请使用如下的numpy数组:

import numpy as np

a = np.ones((3,2))        # a 2D array with 3 rows, 2 columns, filled with ones
b = np.array([1,2,3])     # a 1D array initialised using a list [1,2,3]
c = np.linspace(2,3,100)  # an array with 100 points beteen (and including) 2 and 3

print(a*1.5)  # all elements of a times 1.5
print(a.T+b)  # b added to the transpose of a

这些numpy数组可以从磁盘保存和加载(甚至压缩),并且包含大量元素的复杂计算的速度类似于C。

在科学环境中大量使用。看到这里更多。

For calculations, use numpy arrays like this:

import numpy as np

a = np.ones((3,2))        # a 2D array with 3 rows, 2 columns, filled with ones
b = np.array([1,2,3])     # a 1D array initialised using a list [1,2,3]
c = np.linspace(2,3,100)  # an array with 100 points beteen (and including) 2 and 3

print(a*1.5)  # all elements of a times 1.5
print(a.T+b)  # b added to the transpose of a

these numpy arrays can be saved and loaded from disk (even compressed) and complex calculations with large amounts of elements are C-like fast.

Much used in scientific environments. See here for more.


回答 6

JohnMachin的评论应该是真正的答案。我认为所有其他答案只是解决方法!所以:

array=[0]*element_count

JohnMachin’s comment should be the real answer. All the other answers are just workarounds in my opinion! So:

array=[0]*element_count

回答 7

一些贡献表明python中的数组由列表表示。这是不正确的。Python array()在标准库模块arrayarray.array()”中具有独立的实现,因此将两者混淆是不正确的。列表是python中的列表,因此请谨慎使用所使用的术语。

list_01 = [4, 6.2, 7-2j, 'flo', 'cro']

list_01
Out[85]: [4, 6.2, (7-2j), 'flo', 'cro']

list和之间有一个非常重要的区别array.array()。虽然这两个对象都是有序序列,但array.array()是有序均质序列,而列表是非均质序列。

A couple of contributions suggested that arrays in python are represented by lists. This is incorrect. Python has an independent implementation of array() in the standard library module arrayarray.array()” hence it is incorrect to confuse the two. Lists are lists in python so be careful with the nomenclature used.

list_01 = [4, 6.2, 7-2j, 'flo', 'cro']

list_01
Out[85]: [4, 6.2, (7-2j), 'flo', 'cro']

There is one very important difference between list and array.array(). While both of these objects are ordered sequences, array.array() is an ordered homogeneous sequences whereas a list is a non-homogeneous sequence.


回答 8

您无需在Python中声明任何内容。您只需要使用它。我建议您从http://diveintopython.net之类的东西开始。

You don’t declare anything in Python. You just use it. I recommend you start out with something like http://diveintopython.net.


回答 9

我通常只是做a = [1,2,3]一个实际上是一个,listarrays看看这个正式定义

I would normally just do a = [1,2,3] which is actually a list but for arrays look at this formal definition


回答 10

为了增加Lennart的答案,可以这样创建一个数组:

from array import array
float_array = array("f",values)

其中可以采取一个元组,列表的形式,或np.array,但不是数组:

values = [1,2,3]
values = (1,2,3)
values = np.array([1,2,3],'f')
# 'i' will work here too, but if array is 'i' then values have to be int
wrong_values = array('f',[1,2,3])
# TypeError: 'array.array' object is not callable

并且输出仍然是相同的:

print(float_array)
print(float_array[1])
print(isinstance(float_array[1],float))

# array('f', [1.0, 2.0, 3.0])
# 2.0
# True

list的大多数方法也适用于数组,常见的方法是pop(),extend()和append()。

从答案和评论来看,似乎数组数据结构并不流行。我喜欢它,就像人们可能会更喜欢元组而不是列表一样。

数组结构比列表或np.array具有更严格的规则,这可以减少错误并简化调试,尤其是在处理数字数据时。

尝试将浮点数插入/附加到int数组将引发TypeError:

values = [1,2,3]
int_array = array("i",values)
int_array.append(float(1))
# or int_array.extend([float(1)])

# TypeError: integer argument expected, got float

因此,将要为整数(例如索引列表)的值保留为数组形式可能会防止“ TypeError:列表索引必须为整数,而不是浮点数”,因为可以迭代数组,类似于np.array和list:

int_array = array('i',[1,2,3])
data = [11,22,33,44,55]
sample = []
for i in int_array:
    sample.append(data[i])

烦人的是,将int附加到float数组将导致int成为float,而不会引发异常。

np.array的条目也保留相同的数据类型,但是它不会改变错误,而是会更改其数据类型以适合新条目(通常为double或str):

import numpy as np
numpy_int_array = np.array([1,2,3],'i')
for i in numpy_int_array:
    print(type(i))
    # <class 'numpy.int32'>
numpy_int_array_2 = np.append(numpy_int_array,int(1))
# still <class 'numpy.int32'>
numpy_float_array = np.append(numpy_int_array,float(1))
# <class 'numpy.float64'> for all values
numpy_str_array = np.append(numpy_int_array,"1")
# <class 'numpy.str_'> for all values
data = [11,22,33,44,55]
sample = []
for i in numpy_int_array_2:
    sample.append(data[i])
    # no problem here, but TypeError for the other two

在分配期间也是如此。如果指定了数据类型,则np.array将在可能的情况下将条目转换为该数据类型:

int_numpy_array = np.array([1,2,float(3)],'i')
# 3 becomes an int
int_numpy_array_2 = np.array([1,2,3.9],'i')
# 3.9 gets truncated to 3 (same as int(3.9))
invalid_array = np.array([1,2,"string"],'i')
# ValueError: invalid literal for int() with base 10: 'string'
# Same error as int('string')
str_numpy_array = np.array([1,2,3],'str')
print(str_numpy_array)
print([type(i) for i in str_numpy_array])
# ['1' '2' '3']
# <class 'numpy.str_'>

或者,本质上:

data = [1.2,3.4,5.6]
list_1 = np.array(data,'i').tolist()
list_2 = [int(i) for i in data]
print(list_1 == list_2)
# True

而数组只会给出:

invalid_array = array([1,2,3.9],'i')
# TypeError: integer argument expected, got float

因此,对特定于类型的命令使用np.array不是一个好主意。数组结构在这里很有用。list保留值的数据类型。

对于某些问题,我感到有些讨厌:数据类型在array()中指定为第一个参数,但是(通常)在np.array()中指定为第二个参数。:|

与C的关系在这里引用: Python列表与数组-何时使用?

祝您探索愉快!

注意:数组的类型化和相当严格的性质更倾向于C而不是Python,并且通过设计,Python在其函数中没有许多特定于类型的约束。它的不受欢迎也给协作工作带来了积极的反馈,而替换它通常需要附加的[文件中x的int(x)]。因此,忽略数组的存在是完全可行和合理的。它不应该以任何方式阻碍我们大多数人。:D

To add to Lennart’s answer, an array may be created like this:

from array import array
float_array = array("f",values)

where values can take the form of a tuple, list, or np.array, but not array:

values = [1,2,3]
values = (1,2,3)
values = np.array([1,2,3],'f')
# 'i' will work here too, but if array is 'i' then values have to be int
wrong_values = array('f',[1,2,3])
# TypeError: 'array.array' object is not callable

and the output will still be the same:

print(float_array)
print(float_array[1])
print(isinstance(float_array[1],float))

# array('f', [1.0, 2.0, 3.0])
# 2.0
# True

Most methods for list work with array as well, common ones being pop(), extend(), and append().

Judging from the answers and comments, it appears that the array data structure isn’t that popular. I like it though, the same way as one might prefer a tuple over a list.

The array structure has stricter rules than a list or np.array, and this can reduce errors and make debugging easier, especially when working with numerical data.

Attempts to insert/append a float to an int array will throw a TypeError:

values = [1,2,3]
int_array = array("i",values)
int_array.append(float(1))
# or int_array.extend([float(1)])

# TypeError: integer argument expected, got float

Keeping values which are meant to be integers (e.g. list of indices) in the array form may therefore prevent a “TypeError: list indices must be integers, not float”, since arrays can be iterated over, similar to np.array and lists:

int_array = array('i',[1,2,3])
data = [11,22,33,44,55]
sample = []
for i in int_array:
    sample.append(data[i])

Annoyingly, appending an int to a float array will cause the int to become a float, without throwing an exception.

np.array retain the same data type for its entries too, but instead of giving an error it will change its data type to fit new entries (usually to double or str):

import numpy as np
numpy_int_array = np.array([1,2,3],'i')
for i in numpy_int_array:
    print(type(i))
    # <class 'numpy.int32'>
numpy_int_array_2 = np.append(numpy_int_array,int(1))
# still <class 'numpy.int32'>
numpy_float_array = np.append(numpy_int_array,float(1))
# <class 'numpy.float64'> for all values
numpy_str_array = np.append(numpy_int_array,"1")
# <class 'numpy.str_'> for all values
data = [11,22,33,44,55]
sample = []
for i in numpy_int_array_2:
    sample.append(data[i])
    # no problem here, but TypeError for the other two

This is true during assignment as well. If the data type is specified, np.array will, wherever possible, transform the entries to that data type:

int_numpy_array = np.array([1,2,float(3)],'i')
# 3 becomes an int
int_numpy_array_2 = np.array([1,2,3.9],'i')
# 3.9 gets truncated to 3 (same as int(3.9))
invalid_array = np.array([1,2,"string"],'i')
# ValueError: invalid literal for int() with base 10: 'string'
# Same error as int('string')
str_numpy_array = np.array([1,2,3],'str')
print(str_numpy_array)
print([type(i) for i in str_numpy_array])
# ['1' '2' '3']
# <class 'numpy.str_'>

or, in essence:

data = [1.2,3.4,5.6]
list_1 = np.array(data,'i').tolist()
list_2 = [int(i) for i in data]
print(list_1 == list_2)
# True

while array will simply give:

invalid_array = array([1,2,3.9],'i')
# TypeError: integer argument expected, got float

Because of this, it is not a good idea to use np.array for type-specific commands. The array structure is useful here. list preserves the data type of the values.

And for something I find rather pesky: the data type is specified as the first argument in array(), but (usually) the second in np.array(). :|

The relation to C is referred to here: Python List vs. Array – when to use?

Have fun exploring!

Note: The typed and rather strict nature of array leans more towards C rather than Python, and by design Python does not have many type-specific constraints in its functions. Its unpopularity also creates a positive feedback in collaborative work, and replacing it mostly involves an additional [int(x) for x in file]. It is therefore entirely viable and reasonable to ignore the existence of array. It shouldn’t hinder most of us in any way. :D


回答 11

这个怎么样…

>>> a = range(12)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> a[7]
6

How about this…

>>> a = range(12)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> a[7]
6

回答 12

Python将它们称为list。您可以使用方括号和逗号编写列表文字:

>>> [6,28,496,8128]
[6, 28, 496, 8128]

Python calls them lists. You can write a list literal with square brackets and commas:

>>> [6,28,496,8128]
[6, 28, 496, 8128]

回答 13

在Lennart之后,还有numpy,它实现了同类的多维数组。

Following on from Lennart, there’s also numpy which implements homogeneous multi-dimensional arrays.


回答 14

我有一个字符串数组,并且需要一个相同长度的布尔值数组(初始化为True)。这就是我所做的

strs = ["Hi","Bye"] 
bools = [ True for s in strs ]

I had an array of strings and needed an array of the same length of booleans initiated to True. This is what I did

strs = ["Hi","Bye"] 
bools = [ True for s in strs ]

回答 15

您可以创建列表并将其转换为数组,也可以使用numpy模块创建数组。以下是一些说明此问题的示例。Numpy还使使用多维数组更容易。

import numpy as np
a = np.array([1, 2, 3, 4])

#For custom inputs
a = np.array([int(x) for x in input().split()])

您还可以使用reshape函数将此数组整形为2X2矩阵,该函数将输入作为矩阵的尺寸。

mat = a.reshape(2, 2)

You can create lists and convert them into arrays or you can create array using numpy module. Below are few examples to illustrate the same. Numpy also makes it easier to work with multi-dimensional arrays.

import numpy as np
a = np.array([1, 2, 3, 4])

#For custom inputs
a = np.array([int(x) for x in input().split()])

You can also reshape this array into a 2X2 matrix using reshape function which takes in input as the dimensions of the matrix.

mat = a.reshape(2, 2)