简体   繁体   中英

Understanding Specific Python List Comprehension

I am trying to use this code that produces all possible outcomes of a dice roll, given the number of dice and number of sides. This codes works (but I do not quite understand how the list comprehension is working.

def dice_rolls(dice, sides):
   """
   Equivalent to list(itertools.product(range(1,7), repeat=n)) except
   for returning a list of lists instead of a list of tuples.
   """
   result = [[]]
   print([range(1, sides + 1)] * dice)
   for pool in [range(1, sides + 1)] * dice:
      result = [x + [y] for x in result for y in pool]
   return result

Therefore, I am trying to re-write the list comprehension

result = [x + [y] for x in result for y in pool]

into FOR loops to try to make sense of how it is working, but am currently unable to properly do it. Current failed code:

for x in result:
   for y in pool:
      result = [x + [y]]

2nd Question: If I wanted to make this into a generator (because this function is a memory hog if you have enough dice and sides), would I simply just yield each item in the list as it is being produced instead of throwing it into the result list?

EDIT: I came up with a way to break the list comprehension into loops after getting great responses and wanted to capture it:

def dice_rolls(dice, sides):
result = [[]]
for pool in [range(1, sides + 1)] * dice:
    temp_result = []
    for existing_values in result:  # existing_value same as x in list comp.
        for new_values in pool:  # new_value same as y in list comp.
            temp_result.append(existing_values + [new_values])
    result = temp_result
return result

My first instinct for this problem (and list comprehensions in general) would be to use recursion. Though YOU have asked for LOOPS, which is surprisingly challenging.

This is what I came up with;

def dice_rollsj(dice, sides):
    result = [[]]

    for num_dice in range(dice):
        temp_result = []
        for possible_new_values in range(1, sides+1):
            for existing_values in result:
                new_tuple = existing_values + [possible_new_values]
                temp_result.append(new_tuple)
        result = temp_result

I think that you'll get the same correct answers, but the numbers will be differently ordered. This may be due to the way the values are appended to the list. I don't know.... Let me know if this helps.

I tried to add as many lines as I could, because the goal was to expand and understand the comprehension.

you are redefining result with every iteration of the for y in pool loop. I believe what you want is to append the results:

result = []
for x in result:
   for y in pool:
      result.append(x + [y])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM