简体   繁体   English

Python中2D阵列的列表清单

[英]List of Lists to 2D Array in Python

I have a list of lists in Python that holds a mix of values, some are strings and some are tuples. 我在Python中有一个列表列表,其中包含值的混合,有些是字符串,有些是元组。

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

I am wondering if there is a way to easily convert any length list like that to a 2D Array without using Numpy. 我想知道是否有一种方法可以在不使用Numpy的情况下轻松地将任何长度列表转换为2D数组。 I am working with System.Array because that's the format required. 我正在使用System.Array,因为这是必需的格式。 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. 我知道我可以创建一个数组的新实例,然后使用for循环将列表中的所有数据写入其中。 I was just curious if there is a nice Pythonic way of doing that. 我只是好奇是否有一种很好的Pythonic方式。

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

Then I can loop through my data and set the arr values right? 然后我可以遍历数据并设置arr值正确吗?

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, 谢谢,

Ps. PS。 This is for Excel Interop where I can set a whole Range in Excel by setting it to be equal to an Array. 这是针对Excel Interop的,我可以通过将其设置为等于数组来在Excel中设置整个范围。 That's why I want to convert a list to an Array. 这就是为什么我想将列表转换为数组。 Thank you, 谢谢,

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? 我想知道的是Array是一个类型化的对象,是否可以将其成分设置为字符串还是整数? 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? 将其设置为Arrayobject可以确保我可以在其中组合str / int吗?

Also I though I could use this: 我也可以用这个:

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

but it throws an error. 但是会引发错误。 Any ideas? 有任何想法吗?

You can use Array.CreateInstance to create a single, or multidimensional, array. 您可以使用Array.CreateInstance创建一个或多维数组。 Since the Array.CreateInstance method takes in a "Type" you specify any type you want. 由于Array.CreateInstance方法采用“类型”,因此您可以指定所需的任何类型。 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]

Hope this helps. 希望这可以帮助。 Also see the msdn website for examples of how to use Array.CreateInstance. 另请参阅msdn网站,以获取有关如何使用Array.CreateInstance的示例。

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

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