1

I have a list of scores, e.g. [60, 60, 60, 30, 60, 57, 57, 57], and a lookup dict all_scores_to_numerical_scores. The scores represent point values for an individual dart in a game of darts, and the lookup indicates ways to get that score.

When I use

[all_scores_to_numerical_scores[score] for score in scores]

I get a result like

[['T20'], ['T20'], ['T20'], ['D15', 'T10'], ['T20'], ['T19'], ['T19'], ['T19']]

That is, each nested list shows values corresponding to one of the original scores. I want to get a result like this instead:

[['T20'], ['T20'], ['T20'], ['D15'], ['T20'], ['T19'], ['T19'], ['T19']]
[['T20'], ['T20'], ['T20'], ['T10'], ['T20'], ['T19'], ['T19'], ['T19']]

That is, multiple lists, each of which shows a single way to obtain all of the scores.

How can I do this?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
HJA24
  • 410
  • 2
  • 11
  • 33
  • It seems to me that all you need is the `itertools.product` of the resulting list, to get the two lists you want. This will also handle multiple choices in other list positions. – Prune Mar 28 '21 at 06:33
  • The operation you are looking for is called the *cartesian product* of the sublists. I have linked a useful duplicate, and would also encourage you to read the [wikipedia article](https://en.wikipedia.org/wiki/Cartesian_product) on the topic. – Karl Knechtel Mar 28 '21 at 06:37
  • I removed the `defaultdict` tag because the tags are supposed to be for things involved in the part you need help with, not the part that already works. – Karl Knechtel Mar 28 '21 at 06:38

1 Answers1

2

You can use itertools.product to get all possible outcomes. As your program will calculate how you can get a specific score at a time into lists, then you can use that output to product method as following:

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

If you want every value as list (as in question) you can convert the final data to list as:

final_output = [list([v] for v in x) for x in game_branches]
PaxPrz
  • 1,778
  • 1
  • 13
  • 29