How can I print the possible combinations of a list in Python?

后端 未结 3 1187
温柔的废话
温柔的废话 2021-01-17 03:36

My list is:

groupA=[\'Russia\', \'Egypt\', \'Saudi Arabia\', \'Uruguay\']

So I want to print all the unique combinations of teams that will

相关标签:
3条回答
  • 2021-01-17 04:03

    This can do the trick:

    groupA = ['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
    for index, country in enumerate(groupA):
        for rival in groupA[index+1:]:
            print('%s vs %s'%(country, rival) )
    
    0 讨论(0)
  • 2021-01-17 04:04

    This should do what you want:

    groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
    
    for i in range(len(groupA)):
      for j in range(i+1, len(groupA)):
        print("{} Vs. {}".format(groupA[i], groupA[j]))
    

    If you prefer using itertools:

    from itertools import combinations
    
    groupA=['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
    
    for combo in combinations(groupA, 2):
      print("{} Vs. {}".format(combo[0], combo[1]))
    
    0 讨论(0)
  • 2021-01-17 04:12

    Whenever you're thinking of permutations, combinations, Cartesian products, etc, think of the itertools library; it's standard to Python. And if it's not in there have a look at sympy.

    >>> from itertools import combinations
    >>> for c in combinations(groupA, 2):
    ...     '{} Vs. {}'.format(*c)
    ... 
    'Russia Vs. Egypt'
    'Russia Vs. Saudi Arabia'
    'Russia Vs. Uruguay'
    'Egypt Vs. Saudi Arabia'
    'Egypt Vs. Uruguay'
    'Saudi Arabia Vs. Uruguay'
    

    format is a nice alternative for output too.

    0 讨论(0)
提交回复
热议问题