0
votes

I have 2 lists a = [2, 6, 12, 13, 1, 4, 5] and b = [12, 1]. Elements in list b are a subset of list a.

From the above pair of lists, I need to create a list of tuples as following :

[(12,6),(12,2),(1,13),(1,12),(1,6),(1,2)] 

Basically, at the point of intersection of list b and list a, so from above e.g a and b first intersection point is at index 2, the value 12. So create a tuple with the first element from list b and the second element from list a. I am trying this in python, any suggestion for efficiently doing creating this tuple ? Please note, each list can have 100 elements, in it.

2
Sorry, I don't understans what you need... what is the point of intersection of two lists?rodrigo
@rodrigo, I edited it now. Let me know if it is clear now ?Swati

2 Answers

2
votes

I think this is what you want:

In [11]: a=[2,6,12,13,1,4,5]

In [12]: b=[12,1]

In [13]: ans=[]

In [14]: for x in b:
    ind=a.index(x)     #find the index of element in a
    for y in a[:ind]:  #iterate up to that index and append the tuple to a new list 
        ans.append((x,y))
   ....:         

In [15]: ans
Out[15]: [(12, 2), (12, 6), (1, 2), (1, 6), (1, 12), (1, 13)]

using list comprehension:

In [16]: [(x,y) for x in b for y in a[:a.index(x)]]
Out[16]: [(12, 2), (12, 6), (1, 2), (1, 6), (1, 12), (1, 13)]
2
votes

What about this:

a = [2, 6, 12, 13, 1, 4, 5]
b = [12, 1]

sum([ [ (bb,aa) for aa in a[0:a.index(bb)]] for bb in b], [])

The result is:

[(12, 2), (12, 6), (1, 2), (1, 6), (1, 12), (1, 13)]

It returns the lists in the original order, while your example returns the list reversed. If that is a problem you can reverse them easily.