python 如何将符号网格转换为字符串列表

roejwanj  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(128)

to_strings函数的输入是网格,因此网格显示的任何内容都应转换为字符串列表,其中输入示例:

A B C
 1 . . .
 2 . @ .
 3 . O .

输出示例:

['...', '.@.', '.O.']
True

第一个问题是该特定功能,因为它没有提供预期输出

def to_strings(self):
        from itertools import chain

        m_list_tostring=[]
        for i in range(len(self.grid)):
            x=list(chain.from_iterable(self.grid))
            m_list_tostring = ''.join([str(x) for self.grid, i in enumerate(x)])  # to convert the list of characters into a string
        print(x)

    return str(x)

我还遇到了一个特定Assert错误的问题,需要在检查无效输入(字母x应指示无效行的行坐标)时引发该错误,其中“invalid character in row x”,下面显示的代码是我想到的,但它给出了错误

assert i == self.grid[i], "invalid character in row "+i

我需要在构造函数中添加一个额外的可选参数from_strings,如果它存在,这个参数必须是一个字符串列表,其中每个字符串给出棋盘的一行,使用__str__()方法中使用的字符编码,但没有空格和坐标字母。
还有一个方法to_strings(self),它将电路板表示为字符串列表,格式与__init__()方法从from_strings接受的格式相同。
我怎样才能得到预期的输出?

from string import ascii_uppercase as letters
class Board:
#Dictionary created for the colours and the respected symbols
    points = {'E': '.', 'B': '@', 'W': 'O'}
#Constructor
    def __init__(self,size=19,from_strings=None):
        assert 2 <= size <= 26, "Illegal board size: must be between 2 and 26."
        assert type(from_strings) is list,"input is not a list"
        assert len(from_strings)==size, "length of input list does not match size"
        for i in from_strings:
            assert type(i)==str, "row "+i+" is not a string"
            assert len(i)==size,"length of row "+i+" does not match size"
            #assert i== b[i], "invalid character in row "+i
        self.size = size
        self.grid = [['E'] * size for _ in range(size)]
        self.from_strings = [] if from_strings is None else from_strings
       def get_size(self): #Returns the size of the grid created by the constructor
        return self.size

    def __str__(self): #creating the grid
        padding=' ' #Creating a variable with a space assigned so that it acts as a padding to the rows that have a single digit
        heading = '   ' + ' '.join(letters[:self.size]) #Alphabetical heading is created
        lines = [heading] #adding the alphabetical heading into a list named lines to which the rows will be added later
        for r, row in enumerate(self.grid):
            if len(self.grid)<10: #for the grid with a size less than 10 to add the space to the start of the row for the single digits to be aligned
                line = " " +f'{self.size - r} ' + ' '.join(self.points[x] for x in row)
                lines.append(line)
            else: #for the grids that are larger than 9
                if r>9: #for rows 1 to 9 the single digits are aligned according to the first digit from the right of the two digit rows
                    line =f'{self.size - r} ' + ' '.join(self.points[x] for x in row)
                    line=padding+line #adding the space using the variable padding to the row created
                    lines.append(line) #adding the row to the list of rows
                else: #for the rows 10 onwards - as there is no requirement to add a padding it is not added here
                    line = f'{self.size - r} ' + ' '.join(self.points[x] for x in row)#creation of the row
                    lines.append(line) #adding the newly created row to the list of rows
        return '\n'.join(lines)

    def _to_row_and_column(self, coords):
        # destructure coordinates like "B2" to "B" and 2
        alpha, num = coords
        colnum = ord(alpha) - ord('A') + 1
        rownum = self.size - int(num) + 1
        assert 1 <= rownum <= self.size,"row out of range"
        assert 1 <= colnum <= self.size,'column out of range'
        return rownum, colnum

    def set_colour(self, coords, colour_name):
        rownum, colnum = self._to_row_and_column(coords)
        assert len(coords)==2 or len(coords)==3, "invalid coordinates"
        assert colour_name in self.points,"invalid colour name"
        self.grid[rownum - 1][colnum - 1] = colour_name

    def get_colour(self, coords):
        rownum, colnum = self._to_row_and_column(coords)
        return self.grid[rownum - 1][colnum - 1]

    def to_strings(self):
        from itertools import chain
        m_list_tostring=[]
        for i in range(len(self.grid)):
            x=list(chain.from_iterable(self.grid))
            m_list_tostring = ''.join([str(x) for self.grid, i in enumerate(x)])  # to convert the list of characters into a string
            print(x)
        
        return x

b =Board(3, ["O.O", ".@.", "@O."])
print(b)
print(b.to_strings())
c =Board(b.get_size(), b.to_strings())
print(str(b) == str(c))

现在我的代码是这样的
但是,我没有得到预期的输出,如下所示

A B C
 3 O . O
 2 . @ .
 1 @ O .

['O.O', '.@.', '@O.']
True

我得到的代码输出是:

['E', 'E', 'E', 'E', 'E', 'E', 'E', 'W', 'E']
okxuctiv

okxuctiv1#

我自己执行了代码,并做了一些修改,以更接近您想要的答案。
首先,我不知道这一行到底是做什么的,也不知道b代表什么,所以我把它去掉了:
assert i== b[i], "invalid character in row "+i.
然后我看了看_str_method,这是打印类的方法,当你调用:
print(b)
它没有提到self.from_strings
基本上在每一行中,考虑到网格大小的格式样式,打印您在点字典中定义的字母的对应字符,如下所示:
join(self.points[x] for x in row)
由于点和网格是这样的:
self.grid = [['E'] * size for _ in range(size)]
points = {'E': '.', 'B': '@', 'W': 'O'}
它给出输出:

A B C
 3 . . .
 2 . . .
 1 . . .

假设您在使用from_strings参数时希望该类以这种方式打印,我使用了conditional来使用它

def __str__(self): #creating the grid
            padding=' ' #Creating a variable with a space assigned so that it acts as a padding to the rows that have a single digit
            heading = '   ' + ' '.join(letters[:self.size]) #Alphabetical heading is created
            lines = [heading] #adding the alphabetical heading into a list named lines to which the rows will be added later
            for r, row in enumerate(self.grid):
                if len(self.grid)<10: #for the grid with a size less than 10 to add the space to the start of the row for the single digits to be aligned
                    if (self.from_strings):
                        line = " " +f'{self.size - r} ' + ' '.join(self.from_strings[r])
                    else: 
                        line = " " +f'{self.size - r} ' + ' '.join(self.points[x] for x in row)
                    lines.append(line)
                else: #for the grids that are larger than 9
                    if r>9: #for rows 1 to 9 the single digits are aligned according to the first digit from the right of the two digit rows
                        if (self.from_strings):
                            line = f'{self.size - r} ' + ' '.join(self.from_strings[r])
                        else:
                            line =f'{self.size - r} ' + ' '.join(self.points[x] for x in row)
                        line=padding+line #adding the space using the variable padding to the row created
                        lines.append(line) #adding the row to the list of rows
                    else: #for the rows 10 onwards - as there is no requirement to add a padding it is not added here
                        if (self.from_strings):
                            line = f'{self.size - r} ' + ' '.join(self.from_strings[r])
                        else: 
                            line = f'{self.size - r} ' + ' '.join(self.points[x] for x in row)#creation of the row
                        lines.append(line) #adding the newly created row to the list of rows
            return '\n'.join(lines)

并使用与to_strings方法相同的逻辑:

def to_strings(self):
        padding=' '
        lines = [] 
        for r, row in enumerate(self.grid):
            if self.from_strings : 
                lines.append(''.join(self.from_strings[r]))
            else :
                lines.append(''.join(self.points[x] for x in row))
        return lines

输出如下所示:

A B C
 3 O . O
 2 . @ .
 1 @ O .
['O.O', '.@.', '@O.']
True

相关问题