【问题标题】:Selecting choice numbers选择选择号码
【发布时间】:2020-05-20 04:15:11
【问题描述】:

我有一个列表nums,我想使用随机模块从列表中选择一个不是0 的元素。

到目前为止,我有:

nums = [25, 0, 50, 0, 2, 45, 0]

for numbers in nums:
    for numbers != 0:
        s = random.choice(nums)
print(s)

但这似乎不起作用。我希望s 成为[25, 50, 2, 45] 之一我怎样才能做到这一点?

【问题讨论】:

  • 欢迎来到 Stack Overflow!你想提出的确切问题是什么?您可能想阅读How to ask?

标签: python python-3.x list random integer


【解决方案1】:

因为要避免的值是0,所以您也可以将filter 内置函数与bool 一起使用:

s = random.choice(list(filter(bool, nums)))

为避免创建新列表,您可以使用 while 循环:

s = 0
while s == 0:
    s = random.choice(nums)

【讨论】:

    【解决方案2】:

    简单的解决方案:为不同于 0 的数字创建一个空列表。遍历 nums 并将这些数字附加到该列表中。然后,随机选择。

    filtered_nums = []
    for num in nums:
        if num != 0:
            filtered_nums.append(num)
    s = random.choice(filtered_nums)
    

    稍微高级的解决方案:利用python的filter函数。

    filtered_nums = list(filter(lambda x: x != 0, nums))
    s = random.choice(filtered_nums)
    

    Python的filter很酷,非常值得学习使用:https://www.w3schools.com/python/ref_func_filter.asp

    【讨论】:

      【解决方案3】:

      您可以使用以下列表理解,它使用 random.choice 从 nums 中不等于 0 的所有元素的列表中选择。

      >>> s = random.choice([n for n in nums if n != 0])
      

      【讨论】:

        猜你喜欢
        • 2012-05-14
        • 2015-01-31
        • 2014-12-01
        • 1970-01-01
        • 2016-03-10
        • 1970-01-01
        • 1970-01-01
        • 2018-12-17
        • 2011-10-25
        相关资源
        最近更新 更多