-5

How i read the following data in the the bellow format with for loop.

data = [
    [1,'Services',10],
    [2,'Cost Elements',20],
    [3, 'Rules',30],
    [4, 'Manpower', 40]
]

Expected output is::

p = [
    [1,2,3,4],
    ['services','Cost Elements','Rules','Manpower'],
    [10,20,30,40]
]

And:

{
        id:1,
        name:'services',
        value:10
    },
    {
        id:2,
        name:'Cost Elements',
        value:20
    },
    {
        id:1,
        name:'Rules',
        value:30
    },
    {
        id:1,
        name:'Manpower',
        value:40
    }

Please help ..I am beginner in python so couldn't..

psw
  • 45
  • 1
  • 9

1 Answers1

0

It's easier to transpose your list with zip.

>>> data = [
...     [1,'Services',10],
...     [2,'Cost Elements',20],
...     [3, 'Rules',30],
...     [4, 'Manpower', 40]
... ]
>>> 
>>> p = list(zip(*data))
>>> p
[(1, 2, 3, 4), ('Services', 'Cost Elements', 'Rules', 'Manpower'), (10, 20, 30, 40)]

... or with additional transformation of the inner tuples to lists:

>>> p = list(map(list, zip(*data)))
>>> p
[[1, 2, 3, 4], ['Services', 'Cost Elements', 'Rules', 'Manpower'], [10, 20, 30, 40]]

zip will group together all the elements at corresponding positions (e.g. (sublist1[0], sublist2[0], ...)) for any number of iterable arguments.

~edit~

If it must be a for loop, you could do something like this.

>>> result = [[] for _ in range(len(data[0]))]
>>> 
>>> for sublist in data:
...     for i, element in enumerate(sublist):
...         result[i].append(element)
... 
>>> result
[[1, 2, 3, 4], ['Services', 'Cost Elements', 'Rules', 'Manpower'], [10, 20, 30, 40]]

This is clunky and I don't recommend it.

timgeb
  • 76,762
  • 20
  • 123
  • 145