【问题标题】:Python: String formatting together with enumerate? (Producing a nice string representation of a polynomial in a pythonic way)Python:字符串格式化和枚举? (以 Python 方式生成一个很好的多项式字符串表示)
【发布时间】:2020-10-06 08:01:58
【问题描述】:

我开始编写一个小类,它应该在一个变量中表示多项式函数。我知道功能强大的 sympy 模块已经存在,但我认为放置几行代码而不是加载整个 sympy 模块更简单。主要原因是只是简单地使用了我不需要的抽象级别(即处理变量和环)。

这就是我所做的:

class Polynomial:
    """Class representing polynomials."""
    
    def __init__(self, *coefficients):
        self.coefficients = list(coefficients)
        """Coefficients of the polynomial in the order a_0,...a_n."""
     
    def __repr__(self):
        return "Polynomial(%r)" % self.coefficients
            
    def __call__(self, x):    
        res = 0
        for index, coeff in enumerate(self.coefficients):
            res += coeff * x** index
        return res

我还想实现__str___,其输出与 for 循环产生的输出相同:

res = ""
for index, coeff in enumerate(self.coefficients):
    res += str(coeff) + "x^"+str(index)

首先,我希望像 "$r*x^%r" % enumerate(self.coefficients) 这样的东西可以工作,但事实并非如此。我尝试将enumerate(...) 转换为元组,但这也没有解决问题。

对于我可以用于__str__ 的pythonic 单行返回语句有什么想法吗?

【问题讨论】:

    标签: python string string-formatting


    【解决方案1】:

    我不确定我是否正确理解了您的问题,但您可以使用str.formatstr.join 来获取您的字符串。例如:

    coefficients = [2, 5, 1, 8]
    print( '+'.join('{1}*x^{0}'.format(*v) for v in enumerate(coefficients)) )
    

    打印:

    2*x^0+5*x^1+1*x^2+8*x^3
    

    【讨论】:

      猜你喜欢
      • 2019-11-28
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      相关资源
      最近更新 更多