lizaveta - 1 month ago 8
Python Question

# How to know combination of elements from its index in list of all combionations in python

I have all pair combinations from some list:

``````a = [1,2,3,4,5,6]
pairs = [pair for pair in itertools.combinations(a,2)]
print pairs

>>>[(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5), (3, 4), (3, 5), (4, 5)]
``````

How can I know what exactly pair I work with if I know only its index?
Maybe there is some formula? The problem is that my list is too big and I can't just keep in mind all pairs. I need only some particular pairs which I can recognise by index.

Any suggestions?

Thanks!

Answer

Here's a way to generate a pair directly from its index. There's probably a more efficient equation for this, but this is what I came up with after a couple of minutes. :)

``````import itertools

def pair_from_index(a, i):
m = n = len(a) - 1
while i >= n:
i -= n
n -= 1
m -= n
return a[m], a[m + i + 1]

# test

a = list('abcdefg')

for i, t in enumerate(itertools.combinations(a, 2)):
print(i, t, pair_from_index(a, i))
``````

output

``````0 ('a', 'b') ('a', 'b')
1 ('a', 'c') ('a', 'c')
2 ('a', 'd') ('a', 'd')
3 ('a', 'e') ('a', 'e')
4 ('a', 'f') ('a', 'f')
5 ('a', 'g') ('a', 'g')
6 ('b', 'c') ('b', 'c')
7 ('b', 'd') ('b', 'd')
8 ('b', 'e') ('b', 'e')
9 ('b', 'f') ('b', 'f')
10 ('b', 'g') ('b', 'g')
11 ('c', 'd') ('c', 'd')
12 ('c', 'e') ('c', 'e')
13 ('c', 'f') ('c', 'f')
14 ('c', 'g') ('c', 'g')
15 ('d', 'e') ('d', 'e')
16 ('d', 'f') ('d', 'f')
17 ('d', 'g') ('d', 'g')
18 ('e', 'f') ('e', 'f')
19 ('e', 'g') ('e', 'g')
20 ('f', 'g') ('f', 'g')
``````

Update This function isn't as fast as I thought: I made a silly mistake in my test. Oops! But at least it does work properly. :)

Comments