Home > Software design >  Reorganize list/tuple structure
Reorganize list/tuple structure

Time:10-08

In an exercise I am asked to reorganzie a tuple. Given the tuple: temp = ( ("mandag", 16.0), ("tirsdag", 13.0), ("onsdag", 14.0), ("torsdag", 13.0), ("fredag", 15.0), ("lørdag", 13.0), )

I am supposed to write a function called data_reorganize which outputs the following tuple when printed:

(('mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'),(16.0, 13.0, 14.0, 13.0, 15.0, 13.0))

I have managed this, but my code seems too long and chunky:

def data_reorganize(a):
    x = []
    y = []
    for i in a:
        x.append(i[1])
    x = tuple(x)
    for i in a:
        y.append(i[0])
    y = tuple(y)
    return y,x

CodePudding user response:

Try this with zip and the * unpacking operator. Best part about this approach is that its reversible. Use this again on the output to get back the initial input! -

output = tuple(zip(*temp))
output
(('mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag'),
 (16.0, 13.0, 14.0, 13.0, 15.0, 13.0))

Writing it as a function as you have mentioned in the question requirement -

def data_reorganize(temp: tuple):
    return tuple(zip(*temp))

CodePudding user response:

Your code might be ameliorated as follows

def data_reorganize(a):
    x = []
    y = []
    for i in a:
        x.append(i[1])
        y.append(i[0])
    return tuple(y), tuple(x)

Explanation: I integrated two separate for i in a into single and moved conversion to desired datatype into return.

  • Related