1

I have multiple lists of tuples containing two values, such as:

[('0','2'), ('0','2'), ('1','0')]
[('2','2'), ('0','0'), ('0','2')]
[('0','0'), ('2','1'), ('2','1')]
[('0','2'), ('2','0'), ('0','2')]

I want to create a new set of lists that contains tuples in the order that they appear in the list. For instance in the example above, my desired output would be:

[('0','2'), ('2','2'), ('0','0'), ('0','2')]
[('0','2'), ('0','0'), ('2','1'), ('2','0')]
[('1','0'), ('0','2'), ('2','1'), ('0','2')] 

I am having trouble thinking about how to even approach this problem because the tuples do not have unique key values, and the actual lists contain around 500 tuples each. The position in the list is the important quality of my new grouping. Each list is on a new row of the file if that helps.

Does anyone have any advice?

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59

3 Answers3

8

Try this by using simple zip with *:

a = [
       [('0','2'), ('0','2'), ('1','0')],
       [('2','2'), ('0','0'), ('0','2')],
       [('0','0'), ('2','1'), ('2','1')],
       [('0','2'), ('2','0'), ('0','2')]
    ]


list(zip(*a))

Output will be:

[(('0', '2'), ('2', '2'), ('0', '0'), ('0', '2')),
 (('0', '2'), ('0', '0'), ('2', '1'), ('2', '0')),
 (('1', '0'), ('0', '2'), ('2', '1'), ('0', '2'))]
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • Thank you for your reply. Just to be clear, I will need to nest each list into a single list? If I've generated each list using something like: (...code above reading in csv file including importing itertools (it)...) for row_number, row in read_lines(reader, r): row_tuples = list(it.combinations(row, 2)) i would need to add an additional line such as: rows_combined = [row_tuples] – Matthew Lollar Oct 10 '18 at 08:09
  • @MatthewLollar your welcome, I should say yes, it means if you need to do your desired action you will need to load all of your data from your CSV file and convert it to the above format then run the `zip` function. – Mehrdad Pedramfar Oct 10 '18 at 08:30
0

Do something like this perhaps:

a = [[('0','2'), ('0','2'), ('1','0')],
    [('2','2'), ('0','0'), ('0','2')],
    [('0','0'), ('2','1'), ('2','1')],
    [('0','2'), ('2','0'), ('0','2')]]

res = list(map(list, (zip(*a))))
print(res)
BlackBeard
  • 10,246
  • 7
  • 52
  • 62
0

if it is not mendatory for your output to be a list of tuples, you could also do this with numpy:

import numpy as np
arr = np.transpose([[('0','2'), ('0','2'), ('1','0')],
                [('2','2'), ('0','0'), ('0','2')],
                [('0','0'), ('2','1'), ('2','1')],
                [('0','2'), ('2','0'), ('0','2')]], axes=[1,0,2])

it will return a 3D ndarray.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59