问题
I've written this code so that it generates 4 random ints ranging from 1-6 and then remove the smallest number and add it to a list that is returned.
I was reading around and found that list comprehensions are the more "pythonic" solution instead of these small for range loops. I would like to know how to write this code as a list comprehension and any help would be greatly appreciated.
stats = []
for stat in range(6):
score = [random.randint(1, 6) for n in range(4)]
score.remove(min(score))
stats.append(sum(score))
return stats
回答1:
In Python 3.7 or less, you can do this using the following combination of list comprehensions + generator expression:
stats = [sum(score) - min(score) for score in ([random.randint(1, 6) for n in range(4)] for stat in range(6))]
In Python 3.8 (still in beta), you can do it in a simpler way thanks to the new walrus assignment operator:
stats = [sum(score := [random.randint(1, 6) for n in range(4)]) - min(score) for stat in range(6)]
You can try it here.
Testing both approaches:
Comprehensions (<=
Python 3.7):
import random
random.seed(1)
stats = [sum(score) - min(score) for score in ([random.randint(1, 6) for n in range(4)] for stat in range(6))]
print(stats)
Output:
[10, 12, 12, 12, 15, 14]
Comprehensions + walrus (Python 3.8):
import random
random.seed(1)
stats = [sum(score := [random.randint(1, 6) for n in range(4)]) - min(score) for stat in range(6)]
print(stats)
Output:
[10, 12, 12, 12, 15, 14]
回答2:
Here is my attempt:
I define a function to generate score before using the list comprehension.
import random
stats = []
def make_rand_score():
score = [random.randint(1, 6) for n in range(4)]
score.remove(min(score))
return score
stats = [make_rand_score() for i in range(5)]
print(stats)
回答3:
Try with this:
from random import randint
[min([randint(1, 6) for _ in range(4)]) for _ in range(6)]
However this gets a little complex and hard to read so maybe it's not the best solution.
来源:https://stackoverflow.com/questions/57934869/how-to-convert-this-my-code-into-a-list-comprehension