从列和水平线创建矩阵

时间:2018-12-08 08:05:01

标签: python python-3.x

如何使用行和列创建矩阵。 当我打印矩阵时,输出应该是这样的:

O X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
N X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
M X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
L X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
K X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
J X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
I X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
H X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
G X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
F X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
E X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
D X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
C X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
B X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
A X  X  X  X  X  X  X  X  X  X  X  X  X  X  X  
  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14

我认为我需要在字典中使用列表,并使用矩阵来编辑“ X”,以便以后进行编辑。

hall_dictionary = {}
hall_dictionary["merhaba"] = []
rows = 10
columns = 15
x = [[hall_dictionary["merhaba"] for i in range(columns)] for j in range(rows)]

3 个答案:

答案 0 :(得分:1)

您可以将整个数据存储封装为一个类。它可以处理所有“簿记”,您只需使用A...1...来更改X

内部使用一个简单的一维列表:

class Field:
    def __init__(self, rows, cols, init_piece="x"):
        self.rows = rows
        self.cols = cols
        self.field = [init_piece] * rows * cols

    def place_at(self, row, col, piece):
        """Changes one tile on the field. Does all the reverse-engineering to compute 
        1-dim place of A..?,1..? given tuple of coords."""
        def validation():
            """Raises error when out of bounds."""
            error = []
            if not (isinstance(row,str) and len(row) == 1 and row.isalpha()):
                error.append("Use rows between A and {}".format(chr(ord("A") + 
                                                                    self.rows - 1)))
            if not (0 < col <= self.cols):
                error.append("Use columns between 1 and {}".format(self.cols))
            if error:
                error = ["Invalid row/column: {}/{}".format(row,col)] + error
                raise ValueError('\n- '.join(error))
        validation()
        row = ord(row.upper()[0]) - ord("A")  
        self.field[row * self.cols + col - 1] = piece

    def print_field(self):
        """Prints the playing field."""
        for c in range(self.rows - 1,-1,-1):
            ch = chr(ord("A") + c)
            print("{:<4} ".format(ch), end = "")
            print(("{:>2} " * self.cols).format(*self.field[c * self.cols:
                                                 (c + 1) * self.cols], sep = "  "))
        print("{:<4} ".format(""), end = "")
        print(("{:>2} " * self.cols).format(*range(1,self.cols + 1)))

然后您可以像这样使用它:

rows = 10
cols = 15
f = Field(rows,cols)
f.print_field()

# this uses A...? and 1...? to set things
for r,c in [(0,0),("A",1),("ZZ",99),("A",99),("J",15)]:
    try:
        f.place_at(r,c,"i")  # set to 'i'
    except ValueError as e:
        print(e) 
f.print_field()

输出(之前):

J     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
I     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
H     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
G     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
F     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
E     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
D     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
C     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
B     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
A     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
      1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

输出(设置&&之后的内容)

Invalid row/column: 0/0
- Use rows between A and J
- Use columns between 1 and 15
Invalid row/column: ZZ/99
- Use rows between A and J
- Use columns between 1 and 15
Invalid row/column: A/99
- Use columns between 1 and 15

J     x  x  x  x  x  x  x  x  x  x  x  x  x  x  i
I     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
H     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
G     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
F     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
E     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
D     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
C     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
B     x  x  x  x  x  x  x  x  x  x  x  x  x  x  x
A     i  x  x  x  x  x  x  x  x  x  x  x  x  x  x
      1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 

答案 1 :(得分:0)

听起来像二维数组(类似于回答How to define a two-dimensional array in Python),所以类似这样:

vertical = list(string.ascii_uppercase[0:15][::-1]) # ['O', 'N', ..., 'A']
columns = 15

hall_dictionary = {}
hall_dictionary["merhaba"] = [[x for x in range(columns)] for y in vertical]

for i in range(len(vertical)):
    for j in range(columns):
        hall_dictionary["merhaba"][i][j] = 'X'

然后您可以根据需要编制索引:

hall_dictionary["merhaba"][0][1]  # Always prints 'X'

显示整个数组:

for row in hall_dictionary["merhaba"]:
    print(row)

['X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
... 15 rows ...

并分配,更新新值:

hall_dictionary["merhaba"][0][2] = 'O'

for row in hall_dictionary["merhaba"]:
    print(row)

['X', 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X']
... 

确认元素[0][2]已更新。

答案 2 :(得分:0)

如果您有兴趣,也可以使用pandas DataFrame

import pandas as pd

rows = 10
columns = 15

def indexToLetter(index:int):   # This function might be a bit too verbose
    if index == 0:              #   but all this does is convert an
        return 'A'              #   integer index [0, ∞) to an
                                #   alphabetical index [A..Z, AA..ZZ, AAA...]
    ret = ''
    while index > 0:
        length = len(ret)
        letter = chr(ord('A') + index % 26 - [0, 1][length >= 1])
        ret = letter + ret
        index //= 26
    return ret

# create the row labels
rLabels = [*map(indexToLetter, range(rows))]

# create the dataframe, note that we can simplify
# [['X' for i in range(columns)] for j in range(rows)]
# to [['X'] * columns] * rows
df = pd.DataFrame([['X'] * columns] * rows, index=rLabels)
print(df)

输出:

  0  1  2  3  4  5  6  7  8  9  10 11 12 13 14
A  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
B  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
C  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
D  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
E  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
F  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
G  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
H  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
I  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
J  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X

输出看起来很难看,可能不是您想要的。但是有了数据框,操作矩阵和数据表非常方便。

您可以先指定,然后指定(不同于其他解决方案)来访问它。

df[1][0] = 'O'
df[1][2] = 'O'
df[1][3] = 'O'
print(df)

输出:

  0  1  2  3  4  5  6  7  8  9  10 11 12 13 14
A  X  O  X  X  X  X  X  X  X  X  X  X  X  X  X
B  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
C  X  O  X  X  X  X  X  X  X  X  X  X  X  X  X
D  X  O  X  X  X  X  X  X  X  X  X  X  X  X  X
E  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
F  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
G  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
H  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
I  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
J  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X

说,有人想预订大厅的整行'E'

if any(df.loc['E'] == 'O'):  # check if any seats were taken
    print('Error: some seats in Row <E> are taken.')
else:
    df.loc['E'] = 'O'

print(df)

输出:

  0  1  2  3  4  5  6  7  8  9  10 11 12 13 14
A  X  O  X  X  X  X  X  X  X  X  X  X  X  X  X
B  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
C  X  O  X  X  X  X  X  X  X  X  X  X  X  X  X
D  X  O  X  X  X  X  X  X  X  X  X  X  X  X  X
E  O  O  O  O  O  O  O  O  O  O  O  O  O  O  O
F  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
G  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
H  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
I  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X
J  X  X  X  X  X  X  X  X  X  X  X  X  X  X  X

注意:您也可以执行df.iloc[4]访问E行。是否要访问B到E行?使用df.loc['B':'E']df.iloc[1:5]

您还可以通过访问df[<column_index>] = 'O'对列进行相同操作。