H.Y
H.Y

Reputation: 41

Creating a new list based on their position

So there is a list which contains

'3,2,5,4,1','3,1,2,5,4','2,5,1,4,3'

These numbers are part of the same list, HOWEVER they are strings in a list(ie. list 1)

and from this, you say that for the "first row", 3 occurs at position 0, 2 occurs at position 1, 5 at 2 etc. For the "second row", 3 occurs at position 0, 1 occurs at position 1, 2 occurs at position 2 etc.

I would like to create a loop or anything at all (besides using imported functions) to create a final list which looks like

0: [3, 3, 2]
1: [2, 1, 5]
2: [5, 2, 1]
3: [4, 5, 4]
4: [1, 4, 3]

Upvotes: 2

Views: 100

Answers (2)

Kaushik NP
Kaushik NP

Reputation: 6789

Single line of code using Dictionary comprehension and List comprehension :

>>> { col:[row[col] for row in l] for col in range(len(l[0])) }
=> {0: [3, 3, 2], 1: [2, 1, 5], 2: [5, 2, 1], 3: [4, 5, 4], 4: [1, 4, 3]}

#driver values :

IN : l = [[3,2,5,4,1], 
          [3,1,2,5,4],
          [2,5,1,4,3]]

NOTE to OP : what your output suggests is a Dictionary by looking at its structure. A list cannot be defined in the same manner.

EDIT : Since the OP's list is a list of strings, first convert that to a list of int using map and then continue as above.

>>> l = ['3,2,5,4,1', '3,1,2,5,4', '2,5,1,4,3']

>>> l = [list(map(int,s.split(','))) for s in l]

>>> l
=> [[3, 2, 5, 4, 1], [3, 1, 2, 5, 4], [2, 5, 1, 4, 3]]

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336478

Transposition of a two-dimensional list can simply be done using zip()

In [1]: l = [[3,2,5,4,1],
   ...:      [3,1,2,5,4],
   ...:      [2,5,1,4,3]]
In [2]: t = list(zip(*l))
In [3]: t
Out[3]: [(3, 3, 2), (2, 1, 5), (5, 2, 1), (4, 5, 4), (1, 4, 3)]

To output that in the format described above:

In [4]: for n,line in enumerate(t):
   ...:     print("{}: {}".format(n, list(line)))
   ...:
0: [3, 3, 2]
1: [2, 1, 5]
2: [5, 2, 1]
3: [4, 5, 4]
4: [1, 4, 3]

Upvotes: 1

Related Questions