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