-1

I have a function to split the list, example

def split(*arg):
    row = len(arg[0])
    col = len(arg)
    new = [row * col]
    for i in row:
        for j in col:
            new[j][i] = arg[i][j]
    return new

    # this is method for split the list but it is include errors 

Desired output:

list_a = [(1,2,3),(8,9,10),(100,20,15)]

split (list_a) 
[(1,8,100),(2,9,20),(3,10,15)]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Ann
  • 1
  • based on expected output I'd say you are trying to find the [transpose](http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.transpose.html) – Tadhg McDonald-Jensen Mar 01 '16 at 21:03
  • Does this answer your question? [Transpose list of lists](https://stackoverflow.com/questions/6473679/transpose-list-of-lists) – Karl Knechtel Aug 31 '23 at 18:48

2 Answers2

0

This is very similar to Transpose nested list in python.

However, you want a list of tuples as the result, so we don't even need a list comprehension. Just

list_a = [(1,2,3),(8,9,10),(100,20,15)]

zip(*list_a)  # Python 2
# or
list(zip(*list_a))  # Python 3
# [(1, 8, 100), (2, 9, 20), (3, 10, 15)]

This uses argument unpacking and the built-in zip function.

Community
  • 1
  • 1
das-g
  • 9,718
  • 4
  • 38
  • 80
0

based on the desired output it seems you are trying to find the transpose so you could do it with numpy like this:

import numpy
list_a = [(1,2,3),(8,9,10),(100,20,15)]
transpose_a = numpy.transpose(list_a)
print(transpose_a)
#or
#print(list(transpose_a))

But your split is malfunctioning for a few reasons reasons:

  • you are using *arg perameter but not unpacking the argument so you need to call it like split(*list_a)
  • new = [row * col] is creating a new list with one item instead of a two dimensional list.
  • you are iterating over integers instead of using range(row) and range(col).
  • row and col need to be swapped: row = len(arg) and col = len(arg[0]) since you use row as first dimension and col as second.

Although it occurs to me that this is what zip is designed to do so maybe you just need to use that instead.

Community
  • 1
  • 1
Tadhg McDonald-Jensen
  • 20,699
  • 5
  • 35
  • 59