我有这个int来列出键/值对字典。
PrimNeighboursDict = {883: [880, 881, 884], 884: [883, 885], 885: [884, 886, 889], 886: [885, 889, 887, 888]}
我想随机选择一定数量的密钥,然后对于每个选定的密钥列表,我想从这些列表中随机选择一定数量的项目。
e.g。
randomly selected keys:
883,885
randomly select number of items from each key's list:
883: 881
885: 884,889
这是我到目前为止,我随机选择了键:
import random
PrimNeighboursDict = {883: [880, 881, 884], 884: [883, 885], 885: [884, 886, 889], 886: [885, 889, 887, 888]}
randomPrimitiveFilter = node.evalParm('RandomPrimitiveFilter') #a slider to control the number of selected keys
dictlength = len(PrimNeighboursDict) #dictionary length so total number of primitives
for primitives,neighbours in PrimNeighboursDict.items():
d = PrimNeighboursDict.fromkeys(range(dictlength))
keys = random.sample(list(d), randomPrimitiveFilter)
非常感谢任何帮助。
答案 0 :(得分:0)
我使用了字面值2
而不是滑块值,因为我没有滑块。如果我正确理解您的问题,您需要两个步骤。
所以,
randomPrimitiveFilter = 2
# Step 1
sample_keys = random.sample(PrimNeighboursDict.keys(),randomPrimitiveFilter)
# Step 2
for k in sample_keys:
sample_values = random.sample(PrimNeighboursDict[k],randomPrimitiveFilter)
print k, sample_values
这给了我(每次跑步当然会有所不同)
886 [885, 887]
884 [883, 885]