简体   繁体   English

如何在 Python 中声明一个数组?

[英]How to declare an array in Python?

How do I declare an array in Python ?如何在Python 中声明一个数组?

I can't find any reference to arrays in the documentation.我在文档中找不到任何对数组的引用。

variable = []

Now variable refers to an empty list * . 现在variable引用空列表*

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. 在Python中没有办法说“这个变量永远不应该引用除列表之外的任何东西”,因为Python是动态类型的。


* The default built-in Python type is called a list , not an array. *默认的内置Python类型称为列表 ,而不是数组。 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; 这不应该与array模块混淆, array模块提供更接近C array类型的类型; the contents must be homogenous (all of the same type), but the length is still dynamic. 内容必须是同质的(所有相同的类型),但长度仍然是动态的。

You don't actually declare things, but this is how you create an array in Python: 你实际上没有声明事情,但这是你在Python中创建数组的方式:

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

For more info see the array module: http://docs.python.org/library/array.html 有关更多信息,请参阅阵列模块: http//docs.python.org/library/array.html

Now possible you don't want an array, but a list, but others have answered that already. 现在可能你不想要一个数组,而是一个列表,但其他人已经回答了这个问题。 :) :)

This is surprisingly complex topic in Python. 这是Python中令人惊讶的复杂主题。

Practical answer 实际答案

Arrays are represented by class list (see reference and do not mix them with generators ). 数组由类list表示(请参阅参考 ,不要将它们与生成器混合)。

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. 在引擎盖下,Python的list是包含对项的引用的真实数组的包装器。 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] ) 随机访问真的很便宜( arr[6653]arr[0]相同)
  • append operation is 'for free' while some extra space append操作是“免费”,而一些额外的空间
  • insert operation is expensive insert操作很昂贵

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: 另外,请看这张图片,我试图显示数组,引用数组和链表之间最重要的区别: 数组,到处都是数组

I think you (meant)want an list with the first 30 cells already filled. 我认为你(意味着)想要一个已填充前30个单元格的列表。 So 所以

   f = []

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

An example to where this could be used is in Fibonacci sequence. 可以使用它的一个例子是Fibonacci序列。 See problem 2 in Project Euler 请参阅Project Euler中的问题2

这是如何:

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

You don't declare anything in Python. 你没有用Python声明任何东西。 You just use it. 你只需要使用它。 I recommend you start out with something like http://diveintopython.net . 我建议你从http://diveintopython.net开始

A couple of contributions suggested that arrays in python are represented by lists. 一些贡献表明python中的数组由列表表示。 This is incorrect. 这是不正确的。 Python has an independent implementation of array() in the standard library module array " array.array() " hence it is incorrect to confuse the two. Python在标准库模块arrayarray.array() ”中有一个独立的array()实现,因此混淆两者是不正确的。 Lists are lists in python so be careful with the nomenclature used. 列表是python中的列表,因此请小心使用的命名法。

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() . list和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. 虽然这两个对象都是有序序列,但array.array()是有序的齐次序列,而列表是非同构序列。

我通常会做a = [1,2,3] ,这实际上是一个list但对于arrays看看这个正式的定义

for calculations, use numpy arrays like this: 为了计算,使用像这样的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

these numpy arrays can be saved and loaded from disk (even compressed) and complex calculations with large amounts of elements is C-like fast. 这些numpy数组可以从磁盘中保存和加载(甚至是压缩的),并且具有大量元素的复杂计算速度很快。 Much used in scientific environments. 很多用于科学环境。 See here for more... 请看这里了解更多......

To add to Lennart's answer, an array may be created like this: 要添加到Lennart的答案,可以像这样创建一个数组:

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: 其中可以采用元组,列表或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

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(). 列表的大多数方法也使用数组,常见的是pop(),extend()和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. 数组结构比list或np.array具有更严格的规则,这可以减少错误并使调试更容易,尤其是在处理数值数据时。

Attempts to insert/append a float to an int array will throw a TypeError: 尝试将float插入/附加到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

Keeping values which are meant to be integers (eg 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: 保持数组形式的整数值(例如索引列表)可能会阻止“TypeError:list indices必须是整数,而不是float”,因为数组可以迭代,类似于np.array和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. 令人讨厌的是,将一个int附加到float数组将导致int变为float,而不会引发异常。

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): 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

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: 如果指定了数据类型,则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_'>

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. 因此,将np.array用于特定于类型的命令并不是一个好主意。 The array structure is useful here. 数组结构在这里很有用。 list preserves the data type of the values. list保留值的数据类型。

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(). 对于我发现相当讨厌的东西:数据类型被指定为array()中的第一个参数,但(通常)是np.array()中的第二个参数。 :| :|

The relation to C is referred to here: Python List vs. Array - when to use? 与C的关系在这里提到: Python List vs. Array - 何时使用?

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. 注意:数组的类型和相当严格的性质更倾向于C而不是Python,并且通过设计,Python在其函数中没有许多特定于类型的约束。 Its unpopularity also creates a positive feedback in collaborative work, and replacing it mostly involves an additional [int(x) for x in file]. 它的不受欢迎也会在协同工作中产生积极的反馈,而替换它主要涉及额外的[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 :d

How about this... 这个怎么样...

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

JohnMachin's comment should be the real answer. JohnMachin的评论应该是真正的答案。 All the other answers are just workarounds in my opinion! 在我看来,所有其他答案都只是解决方法! So: 所以:

array=[0]*element_count

继Lennart之后,还有numpy实现了均匀的多维数组。

Python calls them lists . Python将它们称为列表 You can write a list literal with square brackets and commas: 您可以使用方括号和逗号编写列表文字:

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

I had an array of strings and needed an array of the same length of booleans initiated to True. 我有一个字符串数组,需要一个与True相同长度的布尔值的数组。 This is what I did 这就是我做的

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

You can create lists and convert them into arrays or you can create array using numpy module. 您可以创建列表并将它们转换为数组,也可以使用numpy模块创建数组。 Below are few examples to illustrate the same. 以下几个例子来说明相同的内容。 Numpy also makes it easier to work with multi-dimensional arrays. 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()])

You can also reshape this array into a 2X2 matrix using reshape function which takes in input as the dimensions of the matrix. 您还可以使用重塑函数将此数组重新整形为2X2矩阵,该函数将输入作为矩阵的维度。

mat = a.reshape(2, 2)
# This creates a list of 5000 zeros
a = [0] * 5000  

You can read and write to any element in this list with a[n] notation in the same as you would with an array.您可以使用 [n] 符号读取和写入此列表中的任何元素,就像使用数组一样。

It does seem to have the same random access performance as an array.它似乎确实具有与数组相同的随机访问性能。 I cannot say how it allocates memory because it also supports a mix of different types including strings and objects if you need it to.我不能说它是如何分配内存的,因为如果需要,它还支持不同类型的混合,包括字符串和对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM