简体   繁体   English

生成联合分配清单

[英]generating list for joint distribution

I'm pretty sure this is an easy problem but I am completely blacking out on how to fix this. 我敢肯定这是一个简单的问题,但是我完全不了解如何解决此问题。 I am trying to work my way through the PGM class on coursera and it starts of with joint probability distribution. 我正在尝试通过Coursera上的PGM课程进行学习,并且从联合概率分布开始。 So I am trying to generate a list of all possible distributions given n variables, where each variable can take on some discrete value between 0...z 所以我试图生成给定n个变量的所有可能分布的列表,其中每个变量可以取0 ... z之间的某个离散值。

so for instance say we have 3 variables, and each can take on values of just 0 and 1 I want to generate this: 例如,假设我们有3个变量,每个变量只能取0和1的值,我想生成此变量:

[[0, 0, 1]
[0, 1, 0]
[1, 0, 0]
[1, 1, 0]
[0, 1, 1]
[1, 1, 1]
[1, 0, 1]
[0, 0, 0]]

I am working in python I am drawing a blank on how to dynamically generate this. 我在python中工作,我正在如何动态生成此空白。

If you prefer list comprehension: 如果您更喜欢列表理解:

[[a, b, c] for a in range(2) for b in range(2) for c in range(2)]

And I forgot to mention that you can use pprint to get the effect you want: 我忘了提到您可以使用pprint获得所需的效果:

>>> import pprint  
>>> pprint.pprint([[a, b, c] for a in range(2) for b in range(2) for c in range(2)])  
[[0, 0, 0],  
 [0, 0, 1],  
 [0, 1, 0],  
 [0, 1, 1],  
 [1, 0, 0],  
 [1, 0, 1],  
 [1, 1, 0],  
 [1, 1, 1]]  
>>>   

It sounds like you want the Cartesian product: 听起来您想要笛卡尔积:

from itertools import product
for x in product([0,1], [0,1], [0,1]):
    print x

[0, 0, 0] [0,0,0]
[0, 0, 1] [0,0,1]
[0, 1, 0] [0,1,0]
[0, 1, 1] [0,1,1]
[1, 0, 0] [1、0、0]
[1, 0, 1] [1、0、1]
[1, 1, 0] [1,1,0]
[1, 1, 1] [1,1,1]

Slight improvement over Nathan's method: 与Nathan方法相比有一些改进:

>>> import itertools
>>> list(itertools.product([0, 1], repeat=3))
[(0, 0, 0),
 (0, 0, 1),
 (0, 1, 0),
 (0, 1, 1),
 (1, 0, 0),
 (1, 0, 1),
 (1, 1, 0),
 (1, 1, 1)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM