Python 带数学符号的字典

Python dictionary with math symbols

我想在 Python 中制作一本字典,但要使用数学符号(因为那时我想用这些符号绘制它)。

所以,我有这样的东西:

    dict_particles = {1: "Gamma", 
              2: "e+",
             -2: "e-",
              3: "mu+", 
             -3: "mu-",
              4: "pi0",
             -4: "pi+",
                  etc...}

例如,我想要希腊字母的符号,而不是名称 "Gamma"。我也想给他们加上上标和下标。

可能吗?

我从未尝试过在其他环境中查看是否可行,但我去年某个时候在 python 3.x 中使用 IDLE 实现了这一点;我使用 alt codes 将希腊字母输入到我的原始代码中,所以我会说

print("δ")
print("φ")

而且它们会毫无问题地打印出文字字符串。

是的,您可以在 Python 代码中使用任何 Unicode 符号,甚至在变量名称中也是如此(适用于 Python 3.x,对于 Python 2.6+ 看).

你也可以使用 unicode 转义 ("π" = "\u03c0")

你用什么来绘制它们?如果你用的是matplotlib,你可以只写latex:

https://matplotlib.org/users/mathtext.html

那么你的字典可能看起来像这样:

dict_particles = {1: r"\gamma", 
              2: r"\epsilon",
                  etc...}

并且 matplotlib 将用正确的符号替换乳胶。

如果您使用 matplotlib.pyplot,您可以简单地使用提到的语法 here:

text = r'$\alpha > \beta$'

其中 matplotlib.pyplot 将翻译成漂亮的希腊符号,例如

plt.title(text)

对于您的具体示例:

dict_particles = {1: r"\Gamma", 
                  2: r"\epsilon+", ...}