【问题标题】:Creating dictionary dynamically in Python在 Python 中动态创建字典
【发布时间】:2014-05-07 11:34:01
【问题描述】:

我有这个名单和号码:

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}

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

非常感谢

【问题讨论】:

  • @神鹰,你是怎么计算概率的?
  • @PadraicCunningham 我有一些来自 XML 文件的数据,不需要计算
  • 问题已编辑,请看一下;)

标签: python dictionary truthtable


【解决方案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 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]]

【讨论】:

  • 酷!完美,除了一件事:我得到的数字是“镜面反射的”,例如第二行应该是 001 而不是 100,你能解释一下怎么做吗?
  • 你的意思是输出应该反转吗?
  • 我不知道矩阵中reverse的确切含义,但是例如我需要[000,001,010,011,100,101,110,111],现在更清楚了吗?
  • 嗯,我明白了。当我回到我的电脑上时,我会编辑我的答案
  • 没问题。您应该编辑您的问题以反映您需要的输出。
【解决方案2】:

您可以使用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}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 2022-12-07
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多