gpt4 book ai didi

python - 在 Python 中生成给定游戏列表的可能组合

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:17:00 26 4
gpt4 key购买 nike

我想从给定的游戏列表中生成可能性的总数,例如 ['France - Germany'。这样,在这种情况下,总结果将是 3 种可能的结果{要么主队获胜,他们平局,要么客队获胜}。

  • 可能的结果是 3
1   FRANCE - GERMANY 12   FRANCE - GERMANY x3   FRANCE - GERMANY 2

And for another case where the list is ['France - Germany', 'Spain - Italia']

  • Possible number of outcomes are 9
1FRANCE - GERMANY 1SPAIN - ITALIA 1 2   FRANCE - GERMANY 1SPAIN - ITALIA x 3   FRANCE - GERMANY 1SPAIN - ITALIA 24   FRANCE - GERMANY xSPAIN - ITALIA 15   FRANCE - GERMANY xSPAIN - ITALIA x6   FRANCE - GERMANY xSPAIN - ITALIA 27   FRANCE - GERMANY 2SPAIN - ITALIA 18   FRANCE - GERMANY 2SPAIN - ITALIA x9   FRANCE - GERMANY 2SPAIN - ITALIA 2

The Following is my code

import itertools

games = ['France - Germany']
case = ["1","X","2"]
results = []
for eachcase in case:
for game in games:
results.append("%s %s" % (game, eachcase))


print("\n".join(results)+ "\n %s" %len(results))

列表中项目的输出是

France - Germany 1
France - Germany X
France - Germany 2

这很好,但随着列表项目数量的增加,它不起作用。在此先感谢您对解决此问题的任何帮助:)

最佳答案

您可以使用列表理解轻松地做到这一点:

fg = [ ("FRANCE-GERMANY",outcome) for outcome in (1,"x",2) ]
for g1 in fg: print(g1)
print("")

si = [ ("SPAIN-ITALY",outcome) for outcome in (1,"x",2) ]
final = [ (g1,g2) for g1 in fg for g2 in si ]
for g1,g2 in final:
print(g1)
print(g2)
print("")

如果你想要一个更通用的方法,itertools 模块中的 product 函数也可以提供帮助:

from itertools import product
fg = list(product(["FRANCE-GERMANY"],(1,"x",2)))
si = list(product(["SPAIN-ITALY"],(1,"x",2)))
final = list(product(fg,si))

关于python - 在 Python 中生成给定游戏列表的可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54962794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com