python建立一个动态增长的真值表 [英] python build a dynamic growing truth table
本文介绍了python建立一个动态增长的真值表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题很简单: 如何以一种优雅的方式在python中建立一个动态增长的真值表?"
My question is simple: "how to build a dynamic growing truth table in python in an elegant way?"
n = 3
for p in False, True:
for q in False, True:
for r in False, True:
print '|{0} | {1} | {2} |'.format(int(p),int(q), int(r))
n = 4
for p in False, True:
for q in False, True:
for r in False, True:
for s in False, True:
print '|{0} | {1} | {2} | {3}'.format(int(p),int(q), int(r), int(s))
我想有一个将n作为参数并建立表的函数,没有必要 打印表,返回代表该表的数据结构也是可以的.
I would like to have a function which takes n as a parameter and builds up the table, it is not necessary to print the table, returning a data structure representing the table is fine also.
推荐答案
使用 itertools.product()
:
table = list(itertools.product([False, True], repeat=n))
n = 3
的结果:
[(False, False, False),
(False, False, True),
(False, True, False),
(False, True, True),
(True, False, False),
(True, False, True),
(True, True, False),
(True, True, True)]
这篇关于python建立一个动态增长的真值表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文