![](/img/trans.png)
[英]create dictionary of values based on matching keys in list from nested dictionary
[英]Random sampling from dictionary list values based on an integar value from another dictionary, with matching keys
我有兩本詞典,其中一本包含可以從中隨機抽樣的列表項:
candidates_to_sample_from = {'PCP3': ['member3', 'member12', 'member17'],
'PCP4': ['member14', 'member15', 'member16']}
另一個具有匹配的鍵和要從成員池中抽取並最終從成員池中刪除的樣本數:
sample_counts = Counter({'PCP3': 2, 'PCP4': 1})
我嘗試了兩種方法,但沒有得到預期的結果。 一種方法是這樣的:
for prov, lst in candidates_to_sample_from.items():
for i, j in sample_counts.items():
candidates_out = random.sample(lst, j)
print(candidates_out)
['member16']
這從第二個項目只產生1選擇人candidate_to_sample_from
但不是兩人誰應該從第一項目選擇。
然后我還嘗試創建一個空列表並附加到它:
candidates_out = []
for prov, lst in candidates_to_sample_from_dict.items():
for i, j in sample_counts.items():
candidates_out.append(random.sample(lst, j))
print(candidates_out)
[['member3', 'member12'], ['members17'], ['member16', 'member14'], ['member16']]
我正在嘗試獲取一個簡單的列表,例如:
candidates_out = ['member3', 'member17', 'member15']
這有兩個從項目一個candidates_to_sample_from
,一個來自第二。 這是一個較小的模型,無論字典的大小和范圍如何,它都應該相同
嘗試這個:
candidates_out = []
for k, v in sample_counts.items():
candidates_out += random.sample(candidates_to_sample_from[k], v)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.