简体   繁体   English

Python - 枚举多维列表

[英]Python - enumerate a multidimensional list

Let's say I have a multidimensional array, foobar :假设我有一个多维数组foobar

foobar = [[[0, 1, 2],
           [3, 4, 5, 6],
           [7, 8]],
          [[9, 10],
           [11, 12, 13, 14, 15],
           [16, 17, 18],
           [19, 20, 21, 22]],
          [[23, 24, 25],
           [26, 27]]]

Note that foobar is jagged.请注意, foobar是锯齿状的。

The thing I need to do is replace each number in foobar with a tuple containing that number and its exact position in foobar .我需要做的是用一个元组替换foobar中的每个数字,该元组包含该数字及其在foobar中的确切 position。 I also need to be able to do this when the number of dimensions and whether or not foobar is jagged is unknown.当维数和foobar是否参差不齐时,我还需要能够执行此操作。

Here is something similar, except it only works for 2 dimensions:这是类似的东西,除了它只适用于二维:

def enum_multidim(data):
    for i, a in enumerate(data):
        for j, b in enumerate(a):
            yield (i, j, b)

Is there a user-defined function that can do what I said above?有没有自定义的function可以做到我上面说的?

Recursive generator for an arbitrary number of dimensions任意维数的递归生成器

Code代码

def enum_multidim(data, t = None):
    if t is None:
        t = ()
    if not isinstance(data, list):
        yield t + (data,)
    else:
        for i, v in enumerate(data):
            yield from enum_multidim(v, t + (i,))

Test测试

for t in enum_multidim(foobar):
    print(t)

# Out:
(0, 0, 0, 0)
(0, 0, 1, 1)
(0, 0, 2, 2)
(0, 1, 0, 3)
(0, 1, 1, 4)
(0, 1, 2, 5)
(0, 1, 3, 6)
(0, 2, 0, 7)
(0, 2, 1, 8)
(1, 0, 0, 9)
(1, 0, 1, 10)
(1, 1, 0, 11)
(1, 1, 1, 12)
(1, 1, 2, 13)
(1, 1, 3, 14)
(1, 1, 4, 15)
(1, 2, 0, 16)
(1, 2, 1, 17)
(1, 2, 2, 18)
(1, 3, 0, 19)
(1, 3, 1, 20)
(1, 3, 2, 21)
(1, 3, 3, 22)
(2, 0, 0, 23)
(2, 0, 1, 24)
(2, 0, 2, 25)
(2, 1, 0, 26)
(2, 1, 1, 27)

So, I saw DarryIG's answer and modified it to fit my style:所以,我看到了 DarryIG 的答案并对其进行了修改以适合我的风格:

def get_dims(data): # some other function I use
    if not isinstance(data, itertypes):
        return 0
    return get_dims(data[0]) + 1
def enum_multidim(data, index = []):
    if get_dims(data) == 0:
        return index + [data]
    return [enum_multidim(x, index + [i]) for i, x in enumerate(data)]

Credit will go to him.信用将go给他。 Thanks so much!非常感谢!

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

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