0

Given a list to generate tuples, for example:

lst =  ['d', '112', 'b', 'c', 'i', 'a', 'e']

output:

[('d','112'), ('d','b'), ('d','c'), ('d','i'), ..., ('a','e')]

Thanks.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241

2 Answers2

1

Try it

import itertools

lst =  ['d', '112', 'b', 'c', 'i', 'a', 'e']

for comb in itertools.combinations(lst, 2):
    print(comb)
rafaelc
  • 57,686
  • 15
  • 58
  • 82
xPain
  • 132
  • 11
1

If you want to keep you code easy to read, nested loops are the most classical solution.

results = []
for i in range(len(lst)):
    for j in range(i + 1, len(lst)):
        results.append((lst[i], lst[j]))

If you want to make it more pythonic, you should know how to use zip function.

results = []
for i in range(len(lst)):
    results += list(zip([lst[i]] * (len(lst) - i - 1), lst[i + 1:]))

If you want to be even crazy, to save your line number, try a recursive lambda function.

f = lambda x: [] if len(x) <= 1 else list(zip([x[0]] * (len(x) - 1), x[1:])) + f(x[1:])

Then f(lst) is what you want.

Anyway, remember that no matter how short your code is, the time complexity remains the same. If you don't really need a super short code, use the simple one will be better for long-term maintenance.