0

我有这个清单和号码:

list = ['B','C']

我的桌子需要的结果是:

B    C    Prob
0    0    x
0    1    x
1    0    x
1    1    x

我怎样才能建立这个真值表(可以有更多的变量,而不仅仅是 3 个)并为该行的概率分配一个数字?

我需要用字典来构建它,我尝试了一些列表理解,但我不知道如何动态生成真值表,考虑到可能有更多/少于 3 个变量。

编辑:更清楚地说,我的目标是拥有这样的字典:

dict = {"B":0/1,"C":0/1,"Prob":arbitraryNumber}

我需要将所有这些字典插入到一个列表中来表示一个表的结构,现在更清楚了吗?

非常感谢

4

2 回答 2

1

您可以使用powerset生成真值表,

def power_set(items):
    n = len(items)
    for i in xrange(2**n):
        combo = []
        for j in xrange(n):
            if (i >> j) % 2 == 1:
                combo.append(1)
            else:
                combo.append(0)
        yield combo    # if you want tuples, change to yield tuple(combo)


In [13]: list(power_set(l))
Out[13]: [[0, 0], [1, 0], [0, 1], [1, 1]]

In [14]: l=['B','C','E']

In [15]: list(power_set(l))
Out[15]: 
[[0, 0, 0],
[1, 0, 0],
 [0, 1, 0],
 [1, 1, 0],
 [0, 0, 1],
 [1, 0, 1],
 [0, 1, 1],
 [1, 1, 1]]

如果要对数据进行字典,请更改yield comboyield tuple(combo)

然后您可以存储键值对,例如:

d={}
for data in power_set(l):
    d[data]="your_calc_prob"
print d
{(0, 1): 'your_calc_prob', (1, 0): 'your_calc_prob', (0, 0): 'your_calc_prob', (1, 1): 'your_calc_prob'}

如果要对输出进行排序,可以使用 sorted() 来制作列表的副本并返回一个列表:

 sorted(list(power_set(l)))
 Out[21]: 
 [[0, 0, 0],
 [0, 0, 1],
 [0, 1, 0],
 [0, 1, 1],
 [1, 0, 0],
 [1, 0, 1],
 [1, 1, 0],
 [1, 1, 1]]

或者您可以使用列表方法 sort() 对列表进行适当的排序:

In [22]: data = list(power_set(l))  
In [23]: data.sort()
In [24]: data
Out[24]: 
[[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[0, 1, 1],
[1, 0, 0],
[1, 0, 1],
[1, 1, 0],
[1, 1, 1]]
于 2014-05-07T12:25:36.370 回答
0

您可以使用itertools.product()生成真值表,然后根据逻辑运算,确定概率。我不知道您想使用哪个逻辑操作,所以让我们每行创建一个字典:

>>> l = ['B', 'C']
>>> truth_table = [dict(zip(l, x)) for x in product((0, 1), repeat=2)]
>>> print(truth_table)
[{'B': 0, 'C': 0}, {'B': 0, 'C': 1}, {'B': 1, 'C': 0}, {'B': 1, 'C': 1}]

为了计算概率,您可能需要一个单独的函数来执行此操作。例如,以 0 和 1 为值的两个键的逻辑析取基本上等同于max().

>>> l.append('Prob')
>>> truth_table = [dict(zip(l, x + (max(x), )) for x in product((0, 1), repeat=2)]
>>> print(truth_table)
[{'B': 0, 'C': 0, 'Prob': 0},
 {'B': 0, 'C': 1, 'Prob': 1},
 {'B': 1, 'C': 0, 'Prob': 1},
 {'B': 1, 'C': 1, 'Prob': 1}]
于 2014-05-07T11:56:06.637 回答