没有循环的Python多维数组初始化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3662475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:08:42  来源:igfitidea点击:

Python multi-dimensional array initialization without a loop

python

提问by Leonid

Is there a way in Python to initialize a multi-dimensional array / list without using a loop?

Python 中有没有一种方法可以在不使用循环的情况下初始化多维数组/列表?

采纳答案by John La Rooy

Sure there isa way

肯定有办法

arr = eval(`[[0]*5]*10`)

or

或者

arr = eval(("[[0]*5]+"*10)[:-1])

but it's horrible and wasteful, so everyone uses loops (usually list comprehensions) or numpy

但它既可怕又浪费,所以每个人都使用循环(通常是列表推导式)或 numpy

回答by John Kugelman

It depends on what you what to initialize the array to, but sure. You can use a list comprehension to create a 5×3 array, for instance:

这取决于您将数组初始化为什么,但可以肯定。您可以使用列表理解来创建 5×3 数组,例如:

>>> [[0 for x in range(3)] for y in range(5)]
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

>>> [[3*y+x for x in range(3)] for y in range(5)]
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]]

Yes, I suppose this still has loops—but it's all done in one line, which I presume is the intended meaning of your question?

是的,我想这仍然有循环 - 但它全部在一行中完成,我认为这是您问题的预期含义?

回答by Jacob Mattison

Sure, you can just do

当然,你可以这样做

mylist = [
            [1,2,3],
            [4,5,6],
            [7,8,9]
         ]

回答by Eric O Lebigot

Depending on your real needs, the de facto "standard" package Numpymight provide you with exactly what you need.

根据您的实际需求,事实上的“标准”包Numpy可能会为您提供您所需要的。

You can for instance create a multi-dimensional array with

例如,您可以创建一个多维数组

numpy.empty((10, 4, 100))  # 3D array

(initialized with arbitrary values) or create the same arrays with zeroseverywhere with

(用任意值初始化)或创建相同的数组,到处都是

numpy.zeros((10, 4, 100))

Numpy is very fast, for array operations.

Numpy 非常快,用于数组操作。

回答by user108088

I don't believe it's possible.

我不相信这是可能的。

You can do something like this:

你可以这样做:

>>> a = [[0] * 5] * 5

to create a 5x5 matrix, but it is repeated objects (which you don't want). For example:

创建一个 5x5 矩阵,但它是重复的对象(您不想要的)。例如:

>>> a[1][2] = 1
[[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]

You almost certainly need to use some kind of loop as in:

您几乎肯定需要使用某种循环,例如:

[[0 for y in range(5)] for x in range(5)]

回答by Brian Hawkins

If you're doing numerical work using Numpy, something like

如果您正在使用 Numpy 进行数值计算,则类似于

x = numpy.zeros ((m,n))
x = numpy.ones ((m,n))

回答by razpeitia

Recursion is your friend :D

递归是你的朋友 :D

It's a pretty naive implementation but it works!

这是一个非常幼稚的实现,但它有效!

dim = [2, 2, 2]

def get_array(level, dimension):
    if( level != len(dimension) ):
        return [get_array(level+1, dimension) for i in range(dimension[level])]
    else:
        return 0

print get_array(0, dim)

回答by Luke404

Python does not have arrays. It has other sequence types ranging from lists to dictionaries without forgetting sets - the right one depends on your specific needs.

Python 没有数组。它还有其他序列类型,从列表到字典,不会忘记集合 - 正确的类型取决于您的特定需求。

Assuming your "array" is actually a list, and "initialize" means allocate a list of lists of NxMelements, you can (pseudocode):

假设您的“数组”实际上是一个列表,而“初始化”意味着分配一个NxM元素列表,您可以(伪代码):

  • for N times: for M times: add an element
  • for N times: add a row of M elements
  • write the whole thing out
  • 对于 N 次:对于 M 次:添加一个元素
  • N次:添加一行M个元素
  • 写出整件事

You say you don't want to loop and that rules out the first two points, but why? You also say you don't want to write the thing down (in response to JacobM), so how would you exactly do that? I don't know of any other way of getting a data structure without either generating it in smaller pieces (looping) or explicitly writing it down - in any programming language.

你说你不想循环并且排除了前两点,但为什么呢?你还说你不想把事情写下来(作为对 JacobM 的回应),那么你会怎么做呢?我不知道有任何其他方法可以获取数据结构,而无需以较小的部分(循环)生成它或明确地将其写下来 - 使用任何编程语言。

Also keep in mind that a initialized but empty list is no better than no list, unless you put data into it. And you don't need to initialize it before putting data...

还要记住,初始化但为空的列表并不比没有列表好,除非您将数据放入其中。而且你不需要在放入数据之前初始化它......

If this isn't a theoretical exercise, you're probably asking the wrong question. I suggest that you explain what do you need to do with that array.

如果这不是理论练习,那么您可能问错了问题。我建议你解释一下你需要对这个数组做什么。

回答by Arnab Datta

a = [[]]
a.append([1,2])
a.append([2,3])

Then

然后

>>> a
[[1, 2], [2, 3]]

回答by Jens Nyman

The following does not use any special library, nor eval:

以下不使用任何特殊库,也不使用 eval:

arr = [[0]*5 for x in range(6)]

and it doesn't create duplicated references:

它不会创建重复的引用:

>>> arr[1][1] = 2
>>> arr
[[0, 0, 0, 0, 0],
 [0, 2, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0]]