r/programminghelp • • Dec 01 '18

[Python] Running a pairwise test for every element in a list

I am running some stats on every pair in my list of datasets. E.g. array[0] versus array[1], array[0] vs array[2], etc.
Is there a good way to do this other than a nested loop?

Thanks!

4 Upvotes

3 comments sorted by

4

u/[deleted] Dec 01 '18

The nature of the problem requires that for each element in the array, the loop must run the array size times. There won't be any more efficient way of doing that besides a nested loop. Edit: assuming the array isn't ordered in some way or anything

1

u/gabensucksass Dec 01 '18

Got it, thanks!

2

u/07734willy Dec 02 '18

Do know that you have some options, but you won't get more than a constant factor speedup from them. Python has many builtin functions that are at their core written in C, and are far faster than writing the same code explicitly in python. So you could try list comprehensions

[my_func(a, b) for i, a in enumerate(arr) for b in arr[i:]]

mapping + combinations

from itertools import combinations
list(map(lambda l:my_func(l[0], l[1]), combinations(arr, 2)))

or anything in between. Typically the more of your code that you replace with builtins and the more specialized those builtins are, the faster your overall code will be. Again though, there is not algorithmic speedup, its just a constant factor due to less object overhead and peephole optimizations.