列出清单在Python二维数组 [英] List of Lists to 2D Array in Python

查看:269
本文介绍了列出清单在Python二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我保存的值的组合在Python列表的列表,一些是字符串,有些是元组。

I have a list of lists in Python that holds a mix of values, some are strings and some are tuples.

data = [[0,1,2],["a", "b", "c"]]

我想知道是否有一种方法可以轻松地将任何长度的名单一样,到一个二维数组,而无需使用numpy的。我与System.Array的工作,因为这是需要的格式。
我知道我可以创建一个数组的新实例,然后使用for循环,从列表中的所有数据写入。我只是好奇,如果有这样做的一个很好的Python的方式。

I am wondering if there is a way to easily convert any length list like that to a 2D Array without using Numpy. I am working with System.Array because that's the format required. I understand that I can create a new instance of an Array and then use for loops to write all data from list to it. I was just curious if there is a nice Pythonic way of doing that.

x = len(data)
y = len(data[0])
arr = Array.CreateInstance(object, x, y)

然后,我可以通过我的数据环路,并设置ARR值吧?

Then I can loop through my data and set the arr values right?

arr = Array.CreateInstance(object, x, y)
for i in range(0, len(data),1):
    for j in range(0,len(data[0]), 1):
        arr.SetValue(data[i][j], i,j)

我想避免循环一样,如果可能的话。谢谢

I want to avoid looping like that if possible. Thank you,

诗。这是为Excel互操作,我可以通过设置它等于阵列设置的整个范围在Excel中。这就是为什么我要一个列表转换为数组。谢谢

Ps. This is for Excel Interop where I can set a whole Range in Excel by setting it to be equal to an Array. That's why I want to convert a list to an Array. Thank you,

这是我想知道的是,数组是一个类型的对象,是有可能其成员设置为字符串或整数?我想我可能会被限制到只有一个。对?如果是这样,是否有任何其他类型的,我可以使用的数据?
是将其设置为ArrayObject的保证,我可以结合STR / INT它里面?

Thing that I am wondering about is that Array is a typed object, is it possible to set its constituents to either string or integer? I think i might be constrained to only one. Right? If so, is there any other type of data that I can use? Is setting it to Arrayobject ensures that I can combine str/int inside of it?

此外,我虽然我可以用这样的:

Also I though I could use this:

arr= Array[Array[object]](map(object, data))

但它抛出一个错误。有任何想法吗?

but it throws an error. Any ideas?

推荐答案

您可以使用的 Array.CreateInstance 来创建一个单一的,或者多维,数组。由于Array.CreateInstance方法接受一个类型指定任何你想要的类型。例如:

You can use Array.CreateInstance to create a single, or multidimensional, array. Since the Array.CreateInstance method takes in a "Type" you specify any type you want. For example:

// gives you an array of string
myArrayOfString = Array.CreateInstance(String, 3)

// gives you an array of integer
myArrayOfInteger = Array.CreateInstance(Int32, 3)

// gives you a multidimensional array of strings and integer
myArrayOfStringAndInteger = [myArrayOfString, myArrayOfInteger]

希望这有助于。还请参阅MSDN网站上的如何使用Array.CreateInstance例子。

Hope this helps. Also see the msdn website for examples of how to use Array.CreateInstance.

这篇关于列出清单在Python二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆