【问题标题】:Retrieving randomically values in a dictionary with specific conditions in Python在 Python 中使用特定条件随机检索字典中的值
【发布时间】:2023-01-04 02:11:56
【问题描述】:

我想从我的字典中提取一个值 >= 0.05 的键。我的字典看起来像这样

{'Bed_to_Toilet': 0.5645161290322581, 
'Sleep': 0.016129032258064516, 
'Morning_Meds': 0.03225806451612903, 
'Watch_TV': 0.0, 
'Kitchen_Activity': 0.04838709677419355, 
'Chores': 0.0, 
'Leave_Home': 0.03225806451612903, 
'Read': 0.0, 
'Guest_Bathroom': 0.08064516129032258, 
'Master_Bathroom': 0.22580645161290322}

我希望 startActivity 是这些键的随机名称,比如我第一次运行我的代码时是 startActivity = Bed_to_Toilet,第二次是 startActivity = Guest_Bathroom,依此类推。 我该怎么做?

我试过这样做

def findFirstActivity(self, startActModel):
   startActivity, freq = random.choice(list(startActModel.items()))
   return startActivity

它工作得很好,我只需要一种添加条件的方法。

【问题讨论】:

    标签: python python-3.x dictionary random


    【解决方案1】:

    1,获取符合您条件的参考键列表:

    candidate_list = [k for k,v in startActModel.items() if v >= 0.05]
    

    然后您可以从该列表中random.choice

    mykey = random.choice(candidate_list)
    

    此时,如果需要,您可以返回并访问所选的值:

    myval = startActModel[mykey]
    

    【讨论】:

      【解决方案2】:

      如果你想保持你的 API 不变。 您可以向findFirstActivity()传递您的字典的过滤版本。 感谢听写理解。

      filtered_startActModel = {k:v for k, v in d.items() if v >= 0.05}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-04
        • 2022-11-04
        • 2023-03-10
        相关资源
        最近更新 更多