看着Decimal我试图转换pi成各种精度.我可以pi.quantize()使用下面的前两个选项进行调用,但它会InvalidOperation使用第三个选项进行调用.精确度pi远不及......
from decimal import Decimal
pi = Decimal('3.1415926535897932384626433832795028841971693993751058209749445'
'923078164062862089986280348253421170679')
print(pi) # prints same as the string above
# just print formatted
print('{:1.7f}'.format(pi))
print(pi.quantize(Decimal('1.0'))) # 3.1
print(pi.quantize(Decimal('1.00'))) # 3.14
print(pi.quantize(Decimal('1.000'))) # raises InvalidOperation
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?我误解了这个功能应该做什么?为什么会发生此异常1.000而不是之前/之后?
同样的异常发生在'0.001'作为参数quantize.
我曾尝试使用New Times New Roman字体而不是学校网络服务器中Bitstream vera sans font的默认字体matplotlib.
我用Times或Helvetica,或得到以下错误Arial.
找不到错误
为了解决这个问题,我询问技术帮助将这些字体上传到服务器.我确认他们已上传.
现在我删除fontList.cache并重新运行代码如下:
import matplotlib.pyplot as plt
import numpy as np
x= np.arange(0,100)
y= 3*x-1
plt.plot(x,y)
plt.xlabel('x',fontdict={"name": "Times New Roman"})
plt.ylabel('y',fontdict={"name": "Times New Roman"})
plt.show()
Run Code Online (Sandbox Code Playgroud)
好处是我不再看到错误信息了,但不好的是,添加fontdict={"name": "Times New Roman"},标签后已经消失了.
没有任何错误,我无法找到原因.
我希望能够将 jupyter 笔记本作为常规 python 文件运行(使用标准 python 解释器)。我面临的问题是,在 python 中,我无法在可用的位置渲染 markdown 对象:
运行下面的代码会像在笔记本中那样呈现,但<IPython.core.display.Markdown object>在仅使用 python 运行时会打印。
from IPython.display import Markdown, display
display(Markdown('# Hello World!'))
Run Code Online (Sandbox Code Playgroud)
我试图想出一种方法来实现这一点,但发现了这个丑陋的解决方法:
from IPython.display import Markdown, display
from IPython import get_ipython
from IPython.core.displaypub import DisplayPublisher
from ipykernel.zmqshell import ZMQDisplayPublisher
display_pub_class = get_ipython().display_pub_class()
def displaymd(strg):
if isinstance(display_pub_class, ZMQDisplayPublisher):
display(Markdown(strg))
elif isinstance(display_pub_class, DisplayPublisher):
print(strg)
else:
# ??
display(strg)
displaymd('# Hello World!')
Run Code Online (Sandbox Code Playgroud)
这看起来很老套!有没有更简单的方法来获取合理display的 Markdown 对象?或者至少有一种更简单的方法来知道是否display能够渲染 markdown?
同样的问题也适用于 Latex、html 和类似的对象。
刚刚找到了一种稍微简单的方法来检查我是否在 ipython 上:
def on_ipython():
if …Run Code Online (Sandbox Code Playgroud) 我有一个简单的HashMap;说HashMap<char, char>。
有没有办法使用std::mem::swap(或任何其他方法)交换此哈希图中的两个元素?
当然,有一种简单的方法来获取值,get然后将它们替换为insert- 但这会触发哈希器两次(一次用于获取,然后用于插入),我正在寻找一种方法来回避第二次哈希器调用(更多内容)出于好奇心而不是为了表现)。
我尝试的是这个(在几个版本中;没有一个有效 - 正如评论中所述:entry即使我通过了编译器,也不会执行我所期望的操作):
use std::collections::HashMap;
use std::mem::swap;
let mut hash_map: HashMap<char, char> = HashMap::default();
hash_map.insert('A', 'Z');
hash_map.insert('B', 'Y');
swap(&mut hash_map.entry('A'), &mut hash_map.entry('B'));
Run Code Online (Sandbox Code Playgroud)
现在编译器抱怨(我明白为什么它应该)
error[E0499]: cannot borrow `hash_map` as mutable more than once at a time
--> tests.rs:103:42
|
103 | swap(&mut hash_map.entry('A'), &mut hash_map.entry('B'));
| ---- -------- ^^^^^^^^ second mutable borrow occurs here
| | |
| | first mutable borrow occurs here …Run Code Online (Sandbox Code Playgroud) 我是python的初学者.我想让任意索引的数组从pto 运行q,而不是从0运行.
如何创建一个q-p+1索引从?p到q?的数组?
我知道我可以在 sphinx 中记录(模块)常量
#: a tuple of primes
primes = (2, 3, 5, 7, 11, 13, 17)
Run Code Online (Sandbox Code Playgroud)
或者
primes = (2, 3, 5, 7, 11, 13, 17)
"""a tuple of primes"""
Run Code Online (Sandbox Code Playgroud)
然后它将出现在 sphinx 生成的文档中;即它看起来像这样:
somemodule.primes
= (2, 3, 5, 7, 11, 13, 17)素数元组
但如果数据是一个很长的列表怎么办?那么我希望能够在文档中包含文档字符串,但在文档中不包含实际数据本身。
这就是我想要在文档中包含的内容:
somemodule.primes素数元组
有什么方法可以实现这个目标吗?
为了完整性:
我运行sphinx-quickstart并启用了 autodoc:
autodoc: automatically insert docstrings from modules (y/n) [n]: y
Run Code Online (Sandbox Code Playgroud)
我唯一添加的index.rst是:
``somemodule``
**************
.. automodule:: somemodule
:members:
Run Code Online (Sandbox Code Playgroud)
并somemodule.py包含这个:
#: a tuple …Run Code Online (Sandbox Code Playgroud) 使用async/await?执行在 Python 中并行运行的两个异步循环的好方法是什么?
我也想过类似下面的代码,但不能换我围绕着如何使用头async/ await/EventLoop在这种特殊情况下。
import asyncio
my_list = []
def notify():
length = len(my_list)
print("List has changed!", length)
async def append_task():
while True:
time.sleep(1)
await my_list.append(random.random())
notify()
async def pop_task():
while True:
time.sleep(1.8)
await my_list.pop()
notify()
loop = asyncio.get_event_loop()
loop.create_task(append_task())
loop.create_task(pop_task())
loop.run_forever()
Run Code Online (Sandbox Code Playgroud)
预期输出:
$ python prog.py
List has changed! 1 # after 1sec
List has changed! 0 # after 1.8sec
List has changed! 1 # after 2sec
List has changed! 2 # …Run Code Online (Sandbox Code Playgroud) 在以下代码中:
import tkinter as tk
class CardShuffling(tk.Tk):
background_colour = '#D3D3D3'
deck_size = 52
def __init__(self):
tk.Tk.__init__(self) # What does this do?
Run Code Online (Sandbox Code Playgroud)
我对最后一行的目的感到困惑.CardShuffling的一个实例继承自来tk.Tk,不是最后一行只是重复已经由...处理过的事情了CardShuffling(tk.Tk)?
根据https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt,dict.clear ()的时间复杂度为O(1)。
据我所知, dict.clear() 与分配 dict = {} 不同,因为 dict.clear() 对同一个字典进行更改,而 dict = {} 创建一个新的字典。
现在,如果 dict.clear() 正在清除同一个 dict 对象,那么它如何在 O(1) 内完成它。
一个tuple在python(在码块)由逗号定义; 括号不是必需的(在以下情况下)。所以这三个都是等效的:
a, b = 1, 2
a, b = (1, 2)
(a, b) = 1, 2
Run Code Online (Sandbox Code Playgroud)
如果我定义一个功能
def f(a, b):
print(a, b)
Run Code Online (Sandbox Code Playgroud)
以这种方式调用它将起作用:
f(2, 3)
Run Code Online (Sandbox Code Playgroud)
这不会:
f((2, 3))
# TypeError: f() missing 1 required positional argument: 'b'
Run Code Online (Sandbox Code Playgroud)
当它们是函数参数时,python如何区别元组?这里的括号是必须的(我明白为什么会这样,我很高兴python可以这样工作!)。
我的问题是:当它们是函数参数时,python如何区别元组。
python ×9
python-3.x ×5
arrays ×1
asynchronous ×1
dictionary ×1
event-loop ×1
fonts ×1
hashmap ×1
jupyter ×1
list ×1
matplotlib ×1
oop ×1
python-3.4 ×1
rust ×1
sage ×1
swap ×1
tkinter ×1
tuples ×1