在Python中动态创建字典

0 投票
2 回答
2313 浏览
提问于 2025-04-18 05:40

我有一个列表和一个数字:

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}

然后我需要把所有这些字典放进一个列表里,以表示表格的结构,这样说清楚了吗?

非常感谢!

2 个回答

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}]
1

你可以通过使用一个叫做幂集的东西来生成真值表。

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 combo改成yield 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]]

撰写回答