【问题标题】:Equavalent operation of mathematica in pythonpython中mathematica的等价运算
【发布时间】:2016-11-19 08:20:58
【问题描述】:

假设:

h=[1,2,3]

在 Mathematica 中有一个操作 N[expr] 给我们:

N[h[0]]=1, N[h[1]]=2, N[h[2]]=3

例如N[h[6]]=0,在 Python 中是这样的吗?

【问题讨论】:

  • 这个示例代码在语法上不是正确的mathematica。你到底想做什么?

标签: python wolfram-mathematica expr


【解决方案1】:

N[expr] 在mathematica 中为您提供表达式的数值。这在做符号数学的数学中是有意义的。

在 Python 中,您通常没有符号表达式(除非使用专门的库,例如 sympy)。

您可以使用int 将对象转换为整数。例如,int(2)int('2')int(2.6) 会产生值 2。 或者您可以使用float 转换为浮点数。

【讨论】:

    【解决方案2】:

    在 Python 中使用 [..] 运算符在 Python 中访问越界值会引发 IndexError

    >>> h = [1, 2, 3]
    >>> h[0]
    1
    >>> h[6]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range
    

    通过捕获IndexError,您可以使用自定义函数进行类似的操作:

    >>> def N(sequence, index, fallback=0):
    ...     try:
    ...         return sequence[index]
    ...     except IndexError:
    ...         return fallback
    ...
    >>> h = [1, 2, 3]
    >>> N(h, 0)
    1
    >>> N(h, 1)
    2
    >>> N(h, 2)
    3
    >>> N(h, 6)
    0
    >>>
    >>> N(h, 6, 9)  # different fallback value other than 0
    9
    

    【讨论】:

    • 我认为最简单的方法是: h=[1,2,3] for n in range(3,100): h.append (0) 但是,我的问题是有什么操作吗?例如通过操作 N。(不定义其他算法)
    • 你也可以使用h.extend([0] * 97)
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2023-03-12
    • 2022-06-30
    相关资源
    最近更新 更多