【问题标题】:How to print all the values of the list?如何打印列表的所有值?
【发布时间】:2020-03-30 22:54:07
【问题描述】:

我有一个看起来像这样的函数 类数据: def init(self, x, y): """ (数据、列表、列表) -> NoneType

    Create a new data object with two attributes: x and y.
    """
    self.x = x
    self.y = y

def num_obs(self):
    """ (Data) -> int

    Return the number of observations in the data set.

    >>> data = Data([1, 2], [3, 4])
    >>> data.num_obs()
    2
    """

    return len(self.x)

def __str__(self):
    """ (Data) -> str
    Return a string representation of this Data in this format:
    x               y
    18.000          120.000
    20.000          110.000
    22.000          120.000
    25.000          135.000
    26.000          140.000
    29.000          115.000
    30.000          150.000
    33.000          165.000
    33.000          160.000
    35.000          180.000
    """
    for i in range(len(self.x)):
        a = self.x[i]
    for i in range(len(self.y)):
        b = self.y[i]
    return ("x               y\n{0:.3f}         {1:.3f}".format(a,b))

当我调用这个函数时,它只返回列表的最后一个数字。

例如:

数据 = 数据([18,20,22,25],[120,110,120,135])

打印(数据)

x y

25.000 135.000

我希望它返回所有数字

【问题讨论】:

标签: python python-3.x list


【解决方案1】:

您的问题需要将字符串连接在一起;不打印它们。您可以将join 方法与生成器表达式一起使用:

    def __str__(self):
        return 'x               y\n' + '\n'.join(
            '{0:.3f}         {1:.3f}'.format(a, b)
            for a, b in zip(self.x, self.y)
        )

这使用zip 作为一种更简单的方法来获取self.xself.y 中相同索引处的数字对。

【讨论】:

    【解决方案2】:

    解决方案

    更改方法__str__() 如下,它会起作用。

    所做的更改是:

    1. 使用zip(self.x, self.y) 而不是range(len(self.x))
    2. 您正在返回字符串中ab 的最后一个值。
    3. 您需要的是一个使用循环开发的字符串,其中a,b 值在每次迭代中都附加到字符串中。
        def __str__(self):
            """ (Data) -> str
            Return a string representation of this Data in this format:
            x               y
            18.000          120.000
            20.000          110.000
            22.000          120.000
            25.000          135.000
            26.000          140.000
            29.000          115.000
            30.000          150.000
            33.000          165.000
            33.000          160.000
            35.000          180.000
            """
            s = "x               y"
            for a,b in zip(self.x, self.y): 
                s += "\n{0:.3f}         {1:.3f}".format(a,b)
            return s
    

    输出:

    data = Data([18,20,22,25],[120,110,120,135])
    print(data)
    
    x               y
    18.000         120.000
    20.000         110.000
    22.000         120.000
    25.000         135.000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多