python - Pairing elements in a nested list -
i have list of lists this.
a = [1, 2, 3, 4] b = [3, 2, 0.3] c = [0.1, 3, 6.8] d = [9, 2.5, 7, 2] x = [a, b, c, d] i want pair them this:
[a, b], [b, a], [a, c], [c, a], [a, d], [d, a], [b, c], [c, b], [b, d], [d, b], [c, d], [d, c] this way it:
for in range(len(x)): j in range(len(x): if i!= j: #todo... print(x[i], x[j]) my question is: there smarter way improve performance? ( when x has 6-7 items, can tell slowing down lot).
any of inputs me lot.
thanks
this comment gave me interesting idea. here is, using itertools.combinations, returns items in order you're looking for.
from itertools import combinations def foo(x): x in combinations(x, 2): yield (x, x[::-1]) # python3.3+ in foo(['a', 'b', 'c', 'd']): print(i) ('a', 'b') ('b', 'a') ('a', 'c') ('c', 'a') ('a', 'd') ('d', 'a') ('b', 'c') ('c', 'b') ('b', 'd') ('d', 'b') ('c', 'd') ('d', 'c') replace ['a', 'b', 'c', 'd'] [a, b, c, d], actual list of lists.
note: on python <3.3, you'd need yield x; yield x[::-1], because yield from isn't supported.
Comments
Post a Comment