如何将我的代码转换为列表理解 [英] How to convert this my code into a list comprehension

查看:53
本文介绍了如何将我的代码转换为列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已编写此代码,以便它生成4个随机整数(范围为1-6),然后删除最小的数字并将其添加到返回的列表中.

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.

我四处阅读,发现列表推导是更"pythonic"的解决方案,而不是较小的范围循环.我想知道如何以列表理解的方式编写此代码,对您的帮助将不胜感激.

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

推荐答案

在python 3.7或更低版​​本中,您可以使用以下列表推导+生成器表达式的组合来做到这一点:

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

在Python 3.8(仍处于beta版)中,借助新的

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

您可以尝试这里.

测试这两种方法:

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)

输出:

[10, 12, 12, 12, 15, 14]

理解力+海象(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)

输出:

[10, 12, 12, 12, 15, 14]

这篇关于如何将我的代码转换为列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆