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