Search code examples
python-3.xtuplesdjango-querysetiterable-unpacking

Python convert a list of 4 tuple into three 2 tuples, joined on the last element in the tuple


From a django query values_list() I have a list of 4 tuples, ie

[('AAA', '123', 'xyz', '111'), ('BBB', '456', 'uvw', '222'), ...]

What I Want is a multiple lists of two tuples, joined on the last element of each tuple, ie

[('AAA', '111'), ('BBB', '222'), ...]

[('123', '111'), ('456', '222'), ...]

[('xyz', '111'), ('uvw', '222'), ...]

I have it working by executing multiple queries in django and getting a values list for the first column with the second one

(myQuery).values_list('col1', 'idCol')

(myQuery).values_list('col2', 'idCol')

(myQuery).values_list('col3', 'idCol')

This solution, however, executes multiple queries, which I dont think is as good for performance.

so I was wondering if there is a way to do what I showed above, converting a list of 4 tuples to three lists of 2 tuples, so that I can use a singe query, and select all of the values at once

Sorry for the ambiguity, hopefully this gives an idea of what I want to accomplish,

Thanks!


Solution

  • A complete function would look like this,

    l1=[('AAA', '123', 'xyz', '111'), ('BBB', '456', 'uvw', '222')]
    
    def f(l):
        l2=[]
        for i in l1:
            for j in range(len(i)-1):
                 l2.append((i[j], i[-1]))
        return l2
    
    l2=f(l1)
    print(l2)
    

    output:

    [('AAA', '111'), ('123', '111'), ('xyz', '111'), ('BBB', '222'), ('456', '222'), ('uvw', '222')]
    

    then you can seperate each element from the list l2 to get your output.