我有一个名为 scores
[60, 60, 60, 60, 60, 57, 57, 57]
此外,我有一个 defaultdict,我all_scores_to_numerical_scores
在其中存储飞镖投掷的所有数字分数。比如60,可以用三元组扔20/T20。30 可以用双 15 / D15 或 T10 打掉。
如果我输入
[all_scores_to_numerical_scores[score] for score in scores]
我得到以下输出
[['T20'], ['T20'], ['T20'], ['T20'], ['T20'], ['T19'], ['T19'], ['T19']]
但是,如果我的变量scores
定义如下:
[60, 60, 60, 30, 60, 57, 57, 57]
我得到
[['T20'], ['T20'], ['T20'], ['D15','T10'], ['T20'], ['T19'], ['T19'], ['T19']]
我应该如何更改我的代码以获取带有两个选项的列表,如下所示的两个列表
[['T20'], ['T20'], ['T20'], ['D15'], ['T20'], ['T19'], ['T19'], ['T19']]
[['T20'], ['T20'], ['T20'], ['T10'], ['T20'], ['T19'], ['T19'], ['T19']]
提前致谢,
获取 defaultdict 的附加信息:
import re
from collections import defaultdict
SCORES = ['D20', 'D19', 'D18', 'D17', 'D18', 'D17', 'D16', 'D15', 'D14', 'D13',
'D12', 'D11', 'D10', 'D9', 'D8', 'D7', 'D6', 'D5', 'D4', 'D3', 'D2', 'D1',
'S20', 'S19', 'S18', 'S17', 'S16', 'S15', 'S14', 'S13', 'S12', 'S11',
'S10', 'S9', 'S8', 'S7', 'S6', 'S5', 'S4', 'S3', 'S2', 'S1', 'DB', 'SB',
'T20', 'T19', 'T18', 'T17', 'T16', 'T15', 'T14', 'T13', 'T12', 'T11',
'T10', 'T9', 'T8', 'T7', 'T6', 'T5', 'T4', 'T3', 'T2', 'T1']
def caculate_numerical_score(score: str) -> int:
if score == 'DB':
return 50
elif score == 'SB':
return 25
elif score.startswith('T'):
return 3 * int(re.findall('\d+', score)[0])
elif score.startswith('D'):
return 2 * int(re.findall('\d+', score)[0])
else:
return int(re.findall('\d+', score)[0])
if __name__ == "__main__":
numerical_scores = {score: caculate_numerical_score(score) for score in SCORES}
all_scores_to_numerical_scores = defaultdict(list)
for score, numerical_score in numerical_scores.items():
all_scores_to_numerical_scores[numerical_score].append(score)
您可以使用itertools.product
来获得所有可能的结果。由于您的程序将计算如何一次将特定分数放入列表中,因此您可以使用该输出product
方法如下:
from itertools import product
game_possibilities = [['T20'], ['T20'], ['T20'], ['D15','T10'], ['T20'], ['T19'], ['T19'], ['T19']]
game_branches = product(*game_possibilites)
# output
[('T20', 'T20', 'T20', 'D15', 'T20', 'T19', 'T19', 'T19'), ('T20', 'T20', 'T20', 'T10', 'T20', 'T19', 'T19', 'T19')]
如果您希望每个值都作为列表(如所讨论的那样),您可以将最终数据转换为:
final_output = [list([v] for v in x) for x in game_branches]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句