-1
lst =[[1,2,'a'],[3,4,'b'],[5,6,'c'],[7,8,'d']]

result = [[1,3,5,7],[2,4,6,8],['a','b','c','d']]

I need to get result list from lst. Is there any way to get the result list.. Irrespective of length of nested list.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Sreekanth
  • 87
  • 2
  • 8

2 Answers2

3

You should be using zip here:

>>> lst =[[1,2,'a'],[3,4,'b'],[5,6,'c'],[7,8,'d']]

# Python 2.7
>>> result = zip(*lst)
>>> result
[(1, 3, 5, 7), (2, 4, 6, 8), ('a', 'b', 'c', 'd')]

In Python 3+, zip returns generator object. In order to get the value as list, you have to explicitly type-cast it as:

# In Python3+
>>> list(zip(*lst))
[(1, 3, 5, 7), (2, 4, 6, 8), ('a', 'b', 'c', 'd')]
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0
listLen,listElemLen = len(lst), len(lst[0])
res = []
for i in range(listElemLen):
     temp = []
     for j in range(listLen):
        temp.append(lst[j][i])
     res.append(temp)
print(res) #[[1,3,5,7],[2,4,6,8],['a','b','c','d']]
Geetanjali
  • 101
  • 1
  • 1
  • 5