我正在尝试了解Python 3.10 中新的结构模式匹配语法。我知道可以匹配这样的文字值:
def handle(retcode):
match retcode:
case 200:
print('success')
case 404:
print('not found')
case _:
print('unknown')
handle(404)
# not found
Run Code Online (Sandbox Code Playgroud)
但是,如果我重构并将这些值移动到模块级变量,则会导致错误,因为语句现在表示结构或模式而不是值:
SUCCESS = 200
NOT_FOUND = 404
def handle(retcode):
match retcode:
case SUCCESS:
print('success')
case NOT_FOUND:
print('not found')
case _:
print('unknown')
handle(404)
# File "<ipython-input-2-fa4ae710e263>", line 6
# case SUCCESS:
# ^
# SyntaxError: name capture 'SUCCESS' makes remaining patterns unreachable
Run Code Online (Sandbox Code Playgroud)
有没有办法使用 match 语句来匹配存储在变量中的值?
python switch-statement python-3.x python-3.10 structural-pattern-matching
我想从Python会话中以一般方式检测它是否由conda管理.
一些不够通用的想法是有用的:
import os
is_conda = 'CONDA_PREFIX' in os.system or 'CONDA_DEFAULT_ENV' in os.system
Run Code Online (Sandbox Code Playgroud)
这似乎不适用于根conda环境,其中并不总是定义这些变量.如果在使用其他Python安装时碰巧激活了conda,它也可能存在误报.
import sys
is_conda = ('anaconda' in sys.executable) or ('miniconda' in sys.executable)
Run Code Online (Sandbox Code Playgroud)
这将适用于用户在默认路径中安装anaconda/miniconda的情况.否则可能会失败.也很容易想象假阳性.
正如在任何方式判断用户的python环境是否为anaconda的答案中所述,您可以在某些情况下检查Python版本字符串:
import sys
is_conda = ('Continuum Analytics' in sys.version) or ('Anaconda' in sys.version)
Run Code Online (Sandbox Code Playgroud)
这适用于从默认通道安装的Python,但这非常脆弱,将来可能会中断,特别是Continuum的公司名称更改.如果从第三方来源(如conda-forge)安装Python,它也可能会失败.
conda导入try:
import conda
except:
is_conda = False
else:
is_conda = True
Run Code Online (Sandbox Code Playgroud)
只要您处于根conda环境中,这通常会失败,但如果您处于conda默认情况下未安装软件包的另一个conda环境中,则通常会失败.
conda看看它是否有效Atto Allas的建议如下:
import subprocess
try:
retcode = subprocess.call(['conda', 'install', …Run Code Online (Sandbox Code Playgroud) 我一直在https://colab.research.google.com上试验Jupyter笔记本,似乎默认它们运行的是Python 2.7.
有没有办法在CoLab上启用Python 3支持?
以下在Python 3中执行时没有错误:
code = """
import math
def func(x):
return math.sin(x)
func(10)
"""
_globals = {}
exec(code, _globals)
Run Code Online (Sandbox Code Playgroud)
但是,如果我尝试捕获局部变量dict,它也会失败NameError:
>>> _globals, _locals = {}, {}
>>> exec(code, _globals, _locals)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-aeda81bf0af1> in <module>()
----> 1 exec(code, {}, {})
<string> in <module>()
<string> in func(x)
NameError: name 'math' is not defined
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况,如何在捕获全局变量和局部变量时执行此代码?
我正在尝试在 altair 中绘制图像数据,特别是尝试在 Jake VDP 的书 - https://jakevdp.github.io/PythonDataScienceHandbook/05.07-support-vector-machines.html中的此链接中复制人脸识别示例。
有没有人在 altair 中绘制图像数据很幸运?
我有一个自定义HTTP请求处理程序,可以简化为这样的:
# Python 3:
from http import server
class MyHandler(server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
# Here's where all the complicated logic is done to generate HTML.
# For clarity here, replace with a simple stand-in:
html = "<html><p>hello world</p></html>"
self.wfile.write(html.encode())
Run Code Online (Sandbox Code Playgroud)
我想对这个处理程序进行单元测试(即确保我do_GET没有例外地执行),而不实际启动Web服务器.是否有任何轻量级方法来模拟,SimpleHTTPServer以便我可以测试此代码?
该图在列的顶部有日期。它们相互流动,使它们难以阅读。有没有办法垂直旋转这些?我在网上找不到解决方案。
rr_st = alt.Chart(dfag).mark_bar().encode(
x=alt.X('rebalance_range:O', title=""),
y=alt.Y('mean(annual_return):Q', title='annual return'),
column= alt.Column('start_date', title=""),
color=alt.Color('rebalance_range:O', title='rebalance range')
)
rr_st
Run Code Online (Sandbox Code Playgroud)
我在 Jupyter 笔记本(不是 JupyterLab)中使用以下方法渲染 Altair 图:
alt.renderers.enable('notebook')
Run Code Online (Sandbox Code Playgroud)
一切正常,但是相对于我的 Jupyter 笔记本的宽度,这些图通常很小。
如果我使用以下方法将笔记本的宽度扩展到屏幕的 100%:
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
Run Code Online (Sandbox Code Playgroud)
Altair 图不会相应地缩放(它们保持相同的大小)。
有什么方法可以缩放渲染图的大小(即,使它们更大),同时仍将它们保留在笔记本中?
谢谢!
能否使 Altair 绘图适合屏幕尺寸,而不是具有像素定义的宽度和高度?我已经阅读过有关 的内容autosize "fit",但我不确定在哪里指定这些内容。
我想在 Altair 中绘制折线图(带有连接的点标记)。我知道如何更改线宽(通过设置strokeWidth),但我不知道如何更改这些点标记的大小。下面是我的代码:
altair.Chart(ys.reset_index()).mark_line(point=True, strokeWidth=5).encode(
x="Time:T",
y="HL:Q",
color=altair.Color(
"Time Series Component",
scale=altair.Scale(scheme="dark2")
),
tooltip=["Time Series Component", "Time", "HL"]
).interactive().properties(
width=1000,
height=500
).configure_axis(
labelFontSize=20,
titleFontSize=20
).configure_legend(
orient="right"
)
Run Code Online (Sandbox Code Playgroud) python ×10
altair ×5
python-3.x ×2
conda ×1
exec ×1
imshow ×1
jupyter ×1
plot ×1
python-3.10 ×1
python-exec ×1
structural-pattern-matching ×1
unit-testing ×1
vega-lite ×1