NameError: name 'array' is not defined in python

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

I get NameError: name 'array' is not defined in python error when I want to create array, for example:

a = array([1,8,3]) 

What am I doing wrong? How to use arrays?

回答1:

If you need a container to hold a bunch of things, then lists might be your best bet:

a = [1,8,3] 

Type

dir([]) 

from a Python interpreter to see the methods that lists support, such as append, pop, reverse, and sort. Lists also support list comprehensions and Python's iterable interface:

for x in a:     print x  y = [x ** 2 for x in a] 


回答2:

You need to import the array method from the module.

from array import array

http://docs.python.org/library/array.html



回答3:

For basic Python, you should just use a list (as others have already noted).

If you are trying to use NumPy and you want a NumPy array:

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

If you don't know what NumPy is, you probably just want the list.



回答4:

You probably don't want an array. Try using a list:

a = [1,8,3] 

Python lists perform like dynamic arrays in many other languages.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!