简体   繁体   English

python中的二维数组(不是列表)

[英]2D array (not list) in python

I want to make a 2D array (not list) from 2 given lists.我想从 2 个给定的列表中创建一个 2D 数组(不是列表)。 How would I do that?我该怎么做? For example, I want to generate a 2D 2by5 array with the list [1,2,3,4,5] and [6,7,5,9,34] And also how would I iterate that array.例如,我想用列表 [1,2,3,4,5] 和 [6,7,5,9,34] 生成一个二维 2by5 数组,以及我将如何迭代该数组。 I have tried this我试过这个

#import the necessary module
import array as arr

list1 = [2,3,5,7,1]
list2 = [13,17,19,23,29]

myarr = arr.array('i')
index = 0
for i in list1:
    myarr[0][index] = i
    index = index+1
index = 0
for i in list2:
    myarr[1][index] = i
    index = index+1

print(myarr)

Got the error得到错误

Traceback (most recent call last):
  File "temp.py", line 10, in <module>
    myarr[0][index] = i
IndexError: array index out of range

from the documentation of the array module:来自 array 模块的文档:

This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers.该模块定义了一个对象类型,它可以紧凑地表示一组基本值:字符、整数、浮点数。 Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained.数组是序列类型,其行为与列表非常相似,只是其中存储的对象类型受到限制。

So, and array is 1D, and you can't have an array of arrays like you can have list of lists.所以,数组是一维的,你不能拥有一个数组数组,就像你可以拥有列表列表一样。 2D arrays are not possible.二维数组是不可能的。 As others have said: Numpy will be your friend here.正如其他人所说:Numpy 将成为你的朋友。

Take an empty array first and take inner array as integer array先取一个空数组,再取内部arrayinteger array
And then append values as follows然后按如下方式附加值

#import the necessary module
import array as arr

list1 = [2,3,5,7,1]
list2 = [13,17,19,23,29]

myarr = []

myarr.insert(0, arr.array('i'))
for i in list1:
    myarr[0].append(i)

myarr.insert(1, arr.array('i'))
for i in list2:
    myarr[1].append(i)

print(myarr)

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

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