【问题标题】:How to convert this my code into a list comprehension如何将我的代码转换为列表理解
【发布时间】:2019-09-14 11:06:04
【问题描述】:

我编写了这段代码,以便它生成 4 个随机整数,范围从 1 到 6,然后删除最小的数字并将其添加到返回的列表中。

我四处阅读,发现列表推导是更“pythonic”的解决方案,而不是这些小的 for range 循环。我想知道如何将此代码编写为列表理解,任何帮助将不胜感激。

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 python-3.x list function list-comprehension


【解决方案1】:

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

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(仍处于测试阶段)中,借助新的 walrus 赋值运算符,您可以以更简单的方式执行此操作:

stats = [sum(score := [random.randint(1, 6) for n in range(4)]) - min(score) for stat in range(6)]

你可以试试here

测试两种方法:

理解(<=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)

输出:

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

【讨论】:

    【解决方案2】:

    这是我的尝试:

    我在使用列表推导之前定义了一个生成分数的函数。

    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】:

      试试这个:

      from random import randint
      [min([randint(1, 6) for _ in range(4)]) for _ in range(6)]
      

      但是,这有点复杂且难以阅读,因此可能不是最佳解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-12
        • 1970-01-01
        • 1970-01-01
        • 2020-04-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多