Giving a list, how can I select element pairs that satisfy some criterion? I know a linear search algorithm can achieve this:
b = []
for i in range(len(a)-1):
for j in range(i+1,len(a)):
if isTrue(a[i],a[j]):
b.append([a[i],a[j]])
Any better solution can do this more efficiency?
Update
@scytale's comment inspired me a solution. But it can not be perfect.
For example, a = [1.2,3.1,0.3,4.2,5.6,2.7,1.1]. I want to get pairs of elements that the sum of which is less than 3.
b = [(x,y) for x in a for y in a if (x+y)<3 and x!=y]
This will give duplicate pairs of:
[(1.2,0.3),(1.2,1.1),(0.3,1.2),(0.3,1.1),(1.1,1.2),(1.1,0.3)]
But what I want is:
[(1.2,0.3),(1.2,1.1),(0.3,1.1)]