-1

I have a list which looks like this

[['Macau', 'United Kingdom', 'India'],
 ['United States', 'China'],
 ['China', 'Australia']]

And I want to have all possible combinations of those countries but combinations need to be limited to the small lists, I dont want them to mix.

For example I want to have

[('Macau', 'India'), ('United Kingdom', 'India'), ('Macau', 'United Kingdom'), ('United States', 'China')...]
martineau
  • 119,623
  • 25
  • 170
  • 301
Axton
  • 83
  • 5
  • Have you tried using `itertools.combinations` or `itertools.product`? – mkrieger1 Apr 06 '22 at 20:19
  • 1
    Does this answer your question? [How to get all possible combinations of a list’s elements?](https://stackoverflow.com/questions/464864/how-to-get-all-possible-combinations-of-a-list-s-elements). Just do this separately for each list in your list-of-lists. – Pranav Hosangadi Apr 06 '22 at 20:21

2 Answers2

1

Possible solution is the following:

from itertools import combinations

lst = [['Macau', 'United Kingdom', 'India'], ['United States', 'China'],  ['China', 'Australia']]

print([list(combinations(group, 2)) for group in lst])

Returns

[[('Macau', 'United Kingdom'),
  ('Macau', 'India'),
  ('United Kingdom', 'India')],
 [('United States', 'China')],
 [('China', 'Australia')]]
gremur
  • 1,645
  • 2
  • 7
  • 20
  • The case is that I dont want to have all possible combinations but to have possible combinations within each single list, I dont want to mix them all. – Axton Apr 06 '22 at 20:49
  • @Axton, code has been updated – gremur Apr 06 '22 at 22:18
1

use set and itertools to find all possible combinations by groupings

import itertools

data=[['Macau', 'United Kingdom', 'India'],
 ['United States', 'China'],
 ['China', 'Australia']]

lst=[]
for item in data:
    result=list(itertools.combinations(set(item), 2))
    lst.append(result)
    #print(result)
    
print(lst)

output:

[[('United Kingdom', 'Macau'), ('United Kingdom', 'India'), ('Macau', 'India')], [('United States', 'China')], [('Australia', 'China')]]
Golden Lion
  • 3,840
  • 2
  • 26
  • 35