from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["x1", "x2", "x3", "F(x1,x2,x3)"]
x.add_row([0,0,0,1])
x.add_row([0,0,1,1])
x.add_row([0,1,0,0])
x.add_row([0,1,1,0])
x.add_row([1,0,0,1])
x.add_row([1,0,1,1])
x.add_row([1,1,0,0])
x.add_row([1,1,1,1])
print(x)
2 ответа
Воспользуйтесь модулем Numpy:
In [38]: import numpy as np # pip install numpy
In [39]: a = np.array([[0,0,0,1],
...: [0,0,1,1],
...: [0,1,0,0],
...: [0,1,1,0],
...: [1,0,0,1],
...: [1,0,1,1],
...: [1,1,0,0],
...: [1,1,1,1]])
In [40]: print(a)
[[0 0 0 1]
[0 0 1 1]
[0 1 0 0]
[0 1 1 0]
[1 0 0 1]
[1 0 1 1]
[1 1 0 0]
[1 1 1 1]]
In [41]: res = a[a[:, 3] == 1]
In [42]: print(res)
[[0 0 0 1]
[0 0 1 1]
[1 0 0 1]
[1 0 1 1]
[1 1 1 1]]
или модулем Pandas:
In [43]: import pandas as pd # pip install pandas
In [44]: df = pd.DataFrame(
...: [[0,0,0,1],
...: [0,0,1,1],
...: [0,1,0,0],
...: [0,1,1,0],
...: [1,0,0,1],
...: [1,0,1,1],
...: [1,1,0,0],
...: [1,1,1,1]],
...: columns = ["x1", "x2", "x3", "F(x1,x2,x3)"]
...: )
In [45]: df
Out[45]:
x1 x2 x3 F(x1,x2,x3)
0 0 0 0 1
1 0 0 1 1
2 0 1 0 0
3 0 1 1 0
4 1 0 0 1
5 1 0 1 1
6 1 1 0 0
7 1 1 1 1
In [46]: res = df[df['F(x1,x2,x3)']==1]
In [47]: res
Out[47]:
x1 x2 x3 F(x1,x2,x3)
0 0 0 0 1
1 0 0 1 1
4 1 0 0 1
5 1 0 1 1
7 1 1 1 1
Because the PrettyTable module itself is able to select only continuous range of rows, and not rows by some condition, you need prepare rows in such a way that you may select from them in advance, before creating a PrettyTable instance.
For example, as a list of rows:
from prettytable import PrettyTable
FIELD_NAMES = ["x1", "x2", "x3", "F(x1,x2,x3)"]
##### Creating your original table from a list of rows #####
rows = [
[0,0,0,1],
[0,0,1,1],
[0,1,0,0],
[0,1,1,0],
[1,0,0,1],
[1,0,1,1],
[1,1,0,0],
[1,1,1,1],
]
x = PrettyTable()
x.field_names = FIELD_NAMES
for row in rows:
x.add_row(row)
##### Creating a new table with selected rows only #####
selected_rows = [row for row in rows if row[3]] == 1]
y = PrettyTable()
y.field_names = FIELD_NAMES
for row in selected_rows:
y.add_row(row)
##### Printing the original and the new tables #####
print(x)
print(y)
F(x1, x2, x3)
?