如何在Python中打印列表的可能组合?

时间:2017-12-07 16:59:02

标签: python loops

我的清单是:

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

所以我想要打印出彼此相互影响的所有团队组合:

Russia Vs. Egypt
Russia Vs. Saudi Arabia
Russia Vs. Uruguay
Egypt Vs. Saudi Arabia
Egypt Vs. Uruguay
Saudi Arabia Vs. Uruguay

我可以使用for循环吗?

3 个答案:

答案 0 :(得分:2)

这应该做你想要的:

az network application-gateway rule create \
--gateway-name AppGateway \
-g RSgroupAppGateway \
-n Rule-HTTP-80-Site \
--rule-type Basic \
--http-listener FE-HTTP-80-Site \
--redirect-config Redirect-Site-toHTTPS

如果您更喜欢使用itertools:

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]))

答案 1 :(得分:2)

这可以解决问题:

groupA = ['Russia', 'Egypt', 'Saudi Arabia', 'Uruguay']
for index, country in enumerate(groupA):
    for rival in groupA[index+1:]:
        print('%s vs %s'%(country, rival) )

答案 2 :(得分:2)

每当你想到排列,组合,笛卡尔积等时,都要想到itertools库;它是Python的标准。如果不在那里,请查看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也是输出的不错选择。