python-3.x 拆分列表中的数组

dxpyg8gm  于 2022-11-19  发布在  Python
关注(0)|答案(2)|浏览(186)

我有一个列表,它包含一个数组,如

ListA = [('8', array([[422, 769, 468, 789],
         [422, 739, 468, 759],
         [422, 709, 468, 729],
         [422, 545, 468, 565],
         [422, 515, 468, 535]]), 'A'),
         ('8', array([[423, 483, 466, 506]]), 'A'),
         ('8', [], 'B'),
         ('9', array([[375, 579, 414, 619],
         [375, 549, 414, 589],
         [375, 519, 414, 559]]), 'C')]

现在,列表中的数组将被拆分,输出如下所示

ListA = [('8', [422, 769, 468, 789], 'A'),
         ('8', [422, 739, 468, 759], 'A'),
         ('8', [422, 709, 468, 729], 'A'),
         ('8', [422, 545, 468, 565], 'A'),
         ('8', [422, 515, 468, 535], 'A'),
         ('8', [423, 483, 466, 506], 'A'),
         ('8', [], 'B'),
         ('9', [375, 579, 414, 619], 'C'),
         ('9', [375, 549, 414, 589], 'C'),
         ('9', [375, 519, 414, 559], 'C')]

有什么办法可以做到这一点吗?

j91ykkif

j91ykkif1#

output = []
for line in ListA:
    number, arr, char = line
    if len(arr) == 0:  #append empty row
        output.append((number, [], char))

    for row in arr:
        output.append((number, row, char))
hc2pp10m

hc2pp10m2#

这是一个flatmap的作业:

def flatmap(func, *iterable):
    return itertools.chain.from_iterable(map(func, *iterable))

def tuplewitharray_to_listoftuples(t):
    n, arr, c = t
    if len(arr) == 0:
        arr = [[]]
    return [(n, row, c) for row in arr]

list(flatmap(tuplewitharray_to_listoftuples, ListA))

输出:

[('8', [422, 769, 468, 789], 'A'),
 ('8', [422, 739, 468, 759], 'A'),
 ('8', [422, 709, 468, 729], 'A'),
 ('8', [422, 545, 468, 565], 'A'),
 ('8', [422, 515, 468, 535], 'A'),
 ('8', [423, 483, 466, 506], 'A'),
 ('8', [], 'B'),
 ('9', [375, 579, 414, 619], 'C'),
 ('9', [375, 549, 414, 589], 'C'),
 ('9', [375, 519, 414, 559], 'C')]

python标准库中没有flatMap函数,但是pyspark和其他语言的标准库中有一个。
有关flatmap的更多信息:

相关问题