【问题标题】:How to add the sum of a dictionary if condition is true如果条件为真,如何添加字典的总和
【发布时间】:2021-07-24 03:20:50
【问题描述】:

我正在研究类似于二十一点的东西。其中只有少数只是用于测试。我从字典中随机化两个不同的键。我遇到的问题是我不知道如何根据条件添加值的总和。我知道 sum() 在这种情况下不起作用,但我想要类似的东西来从 for 循环item 中获取返回,它返回两个元素并将它们加在一起。 提前谢谢!

import random

numbers = {'9': 9, '10': 10, 'J': 10}
numbers_list = list(numbers.keys())

pick_one = random.choice(numbers_list)
pick_two = random.choice(numbers_list)

print(pick_one, pick_two)
for items in numbers:
    if pick_one in numbers_list and pick_two in numbers_list:
        if pick_one == items and pick_two == items:
            total = sum(numbers[items])
            print(total)

【问题讨论】:

  • 你已经使这比它需要的更难了。只是numbers[pick_one] + numbers[pick_two]。
  • 这不是重点。我想让它更简单。如果我有 10 个随机数。然后我必须写十次 numbers[x]。我知道我可以做到这一点,这就是为什么我需要一些帮助,看看我是否可以用一条简单的线让它工作。
  • 那么你就不会创建pick_one 和pick_two。您将创建一个 picks 列表,这样可以很容易地将它们的值相加。
  • 每当你发现自己给变量命名时,你真正想要的是一个列表。
  • if pick_one in numbers_list and pick_two in numbers_list: 的意义何在?您实际上只是从列表中选择了数字...

标签: python dictionary for-loop random


【解决方案1】:
import random

numbers = {'9': 9, '10': 10, 'J': 10}
numbers_list = list(numbers.keys())

picks = [random.choice(numbers_list) for _ in range(2)]
print(picks)

total = sum(numbers[p] for p in picks)
print(total)

【讨论】:

    【解决方案2】:
    from random import choice
    
    numbers = {'9': 9, '10': 10, 'J': 10}   
    total = numbers[choice(list(numbers.keys()))] + numbers[choice(list(numbers.keys()))]  
    print(total)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 2014-07-17
      • 2015-08-19
      • 2018-02-24
      • 2018-10-29
      • 2017-09-21
      • 2020-09-15
      相关资源
      最近更新 更多