0

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!

wil moskal
  • 309
  • 1
  • 14

3 Answers3

1
def f(l):
    return [(i[0], i[-1]) for i in l]
USERNAME GOES HERE
  • 692
  • 1
  • 15
  • 29
1

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.

Prathamesh
  • 1,064
  • 1
  • 6
  • 16
0

Thanks for the help! The solution that ended up working was

def to2TupleList(self, tupleList, i):
        twoTupleList = []
        for t in tupleList:
            twoTupleList.append((t[i], t[-1]))
        return twoTupleList

Then I pass the values list and the index of the value that I want, and it works like a charm!

wil moskal
  • 309
  • 1
  • 14