1

I have a list which has an array like

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')]

Now the array in the list is to be splitted in such a way that output looks like

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')]

Is there any way to to do this ?

Durga Rao
  • 73
  • 6

2 Answers2

2
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))
  • the o/p also contains array ('9', array([374, 519, 413, 560]), 'C')], Can we remove the array like ('9', [374, 519, 413, 560], 'C')] – Durga Rao Jul 21 '20 at 10:06
  • I don't know if I understand correctly, but if you want to skip specific line you can simply add condition: if line != ('9', [374, 519, 413, 560], 'C'): continue – Adrian Stępniak Jul 21 '20 at 10:09
0

This is a job for 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))

output:

[('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')]

There is no flatMap function in the python standard library, but there is one in pyspark, as well as in other languages' standard libraries.

More about flatmap:

Stef
  • 13,242
  • 2
  • 17
  • 28