0

尽我所能,我无法理解为什么 PrettyTable add_row 方法没有在我的 Python 3 代码中打印表体。这是一个评估真值表并打印出来的程序。

如果我使用打印功能,我可以打印出应该由 PrettyTable 的 x.add_row() 方法打印的数据。

#!/usr/bin/env python3

# Write a general truth expresion for a statement ((P or Q) and (P or S or Q) and (P or R))

# import modules
import prettytable

P = [True, True, False, False]
Q = [True, False, True, False]
R = [True, False, True, False]
S = [False, True, False, True]


def print_result(P, Q, R, S, w, x, y, z):
    print(f"[+] Truth Table")

    x = prettytable.PrettyTable(["P","Q", "R", "S", "P or Q", "P or S or Q", "P or R", "(P or Q) and (P or S or Q) and (P or R)"])

    for a, b, c, d, e, f, g, h in zip(P, Q, R, S, w, x, y, z):
        x.add_row([a, b, c, d, e, f, g, h])
            
    print(f"{x}")



def p_or_q(P, Q):
    p_or_q_list = []

    for x, y in zip(P, Q):
        p_or_q_list.append(x or y)
    
    return p_or_q_list


def p_or_s_or_q(P, S, Q):
    p_or_s_or_q_list = []

    for x, y, z in zip(P, S, Q):
        p_or_s_or_q_list.append(x or y or z)

    return p_or_s_or_q_list     


def p_or_r(P, R):
    p_or_r_list = []

    for x, y in zip(P, R):
        p_or_r_list.append(x or y)

    return p_or_r_list  


def all_together(P, Q, R, S):
    all_together_list = []

    for a, b, c, d in zip(P, Q, R, S):
        all_together_list.append((a or b) and (a or d or b) and (a or c))

    return all_together_list    


w = p_or_q(P, Q)
x = p_or_s_or_q(P, S, Q)
y = p_or_r(P, R) 
z = all_together(P, Q, R, S)

print_result(P, Q, R, S, w, x, y, z)    

这就是我得到的输出:

在此处输入图像描述

4

1 回答 1

0

我不知道为什么,但是for循环print_result不喜欢在循环语句中声明的 zip 对象。在那里使用时不会打开包装。如果您首先将zip对象存储在变量中并迭代变量,则它可以正常工作。

def print_result(P, Q, R, S, w, x, y, z):

    print(f"[+] Truth Table")

    x = prettytable.PrettyTable()
    x.field_names = ["P","Q", "R", "S", "P or Q",
                     "P or S or Q", "P or R",
                     "(P or Q) and (P or S or Q) and (P or R)"]

    tuples = zip(P,Q,R,S,w,x,y,z)
    for a, b, c, d, e, f, g, h in tuples:
        x.add_row([a, b, c, d, e, f, g, h])

    print(f"{x}")
于 2021-01-02T06:27:40.633 回答