【问题标题】:__str__ Method returning sets vertically Python__str__ 方法垂直返回集合 Python
【发布时间】:2017-09-19 02:41:04
【问题描述】:

我正在尝试在名为 matrix 的类中实现 str 方法 我当前的代码是

类矩阵(对象):

def __init__(self):  # no modification is needed for this method, but you may modify it if you wish to
    '''Create and initialize your class attributes.'''
    self._matrix = []
    self._rooms = 0

def read_file(self,fp):  #fp is a file pointer
    '''Build an adjacency matrix that you read from a file fp.'''

    rooms = fp.readline()

    rooms = int(rooms)

    self._matrix= [set() for _ in range(rooms+1)]

    for line in fp:
        line=line.strip()
        item=line.split()
        item2=int(item[0])
        item3=int(item[1])
        self._matrix[item2].add(item3)
        self._matrix[item3].add(item2)
    return self._matrix

def __str__(self):
    '''Return the matrix as a string.'''
    s=''
    matrix=self._matrix
    for n in range(len(matrix)-1):
        s=s+"{}:{} ".format(n+1,matrix[n+1])
    return s

当前,当我通过 print(Matrix()) 调用 str 方法时,我得到输出: 1:{2} 2:{1, 3} 3:{2, 4} 4:{3, 5} 5:{4, 6} 6:{5}

我要打印的是:

1:2

2:1 3

3:2 4

4:3 5

5:4 6

6:5

有什么建议吗?

【问题讨论】:

    标签: python string class methods


    【解决方案1】:

    不要直接将集合的字符串表示形式添加到输出字符串,而是将集合中的每个项目转换为字符串,然后将元素连接到一个新字符串,并以" " 作为分隔符。为每一行添加一个换行符 ("\n")。

    s+= "%d: %s\n" % (n+1, " ".join([str(x) for x in matrix[n+1]]))
    

    【讨论】:

    • 咳嗽 " ".join(...)
    • 你不需要字符串,只需执行'" "'.join(str(x) for x in matrix[n + 1])
    • 我得到一个模块'string'没有属性'join'错误?
    • 确实" ".join(...)更pythonic,不需要导入string模块
    猜你喜欢
    • 1970-01-01
    • 2015-06-18
    • 2016-07-05
    • 2023-03-13
    • 2013-12-13
    • 2017-08-25
    • 2015-05-08
    • 1970-01-01
    • 2014-12-03
    相关资源
    最近更新 更多