0

I often use Python. When I transposed a 2D array in python. I will code like this:

matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
# method 1
transposed = [[row[i] for row in matrix] for i in range(4)]
# method 2, usually code in this way
transposed = list(map(list, zip(*matrix)))

Output would be:

[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

Howerver, in swift, zip() can only take 2 parameters.
I can write a function to do the transpose.
But I wonder if there is a way to do this elegantly in swift, too.

cs95
  • 379,657
  • 97
  • 704
  • 746
codingBoy
  • 33
  • 5
  • 1
    My answer in the duplicate question shows a pretty elegant way to do it. It's quite a bit more text, but that lets it be encapsulated into a function, which is even generic, to support as many types as possible. You should aim to do this in your python code, as well. Rather than repasting cryptic snippets like `list(map(list, zip(*matrix)))`, you should extract this functionality to a function – Alexander Jun 25 '18 at 06:13
  • Thanks for your comment. You do have an elegant way to do it. – codingBoy Jun 25 '18 at 08:58

0 Answers0