1

I have the following list:

sortedList = [['2', 'f'],['5', 'B'],['8', '6'],['32','@'],['43', 'G'],['76', '.'],['173', 'v'],['200', '.'],['265', 'y']]

I am attempting to create a 3x3 matrix from this list so that the output would be the following:

matrix = [['f','B','6'],['@','G','.'],['v','.','y']]

Essentially, I need to find a function that would take the last string of each list and put it into lists 3 strings in length.

taytortot
  • 99
  • 1
  • 2
  • 5

1 Answers1

3

You could use a list comprehension to collect the last string in each item:

In [67]: [item[-1] for item in sortedList]
Out[67]: ['f', 'B', '6', '@', 'G', '.', 'v', '.', 'y']

Then, to collect these items in groups of 3, use the grouper recipe:

In [68]: zip(*[(item[-1] for item in sortedList)]*3)
Out[68]: [('f', 'B', '6'), ('@', 'G', '.'), ('v', '.', 'y')]

Note that the grouper recipe, zip(*[iterator]*3) calls for an iterator, so the list comprehension was replaced by a generator expression.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Wow, a generator inside an multiplied array, nice. But it might be unclear how it works. – Arpegius Apr 14 '14 at 00:00
  • 1
    I've tried to write an explanation of how the grouper recipe works [here](http://stackoverflow.com/a/17516752/190597), but I fear it is not very good. – unutbu Apr 14 '14 at 00:02
  • Worked perfectly. Needed to have the user choose what to multiply by at the end, so I replaced "3" with a command line argument. – taytortot Apr 14 '14 at 20:27