我有一个名字叫scores的列表
[60, 60, 60, 60, 60, 57, 57, 57]此外,我还有一个名为all_scores_to_numerical_scores的默认值,在这里我存储了所有飞镖抛出的数字分数。例如,可以用三重值20 / T20抛出60。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)发布于 2021-03-28 06:34:19
您可以使用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]https://stackoverflow.com/questions/66838893
复制相似问题