在开始学习lisp时,我遇到了尾递归这个术语.这究竟是什么意思?
language-agnostic algorithm recursion functional-programming tail-recursion
我今天刚与一些同事就python的db-api fetchone vs fetchmany vs fetchall进行了讨论.
我确定每个用例的用例取决于我正在使用的db-api的实现,但一般来说fetchone vs fetchmany vs fetchall的用例是什么?
换句话说是以下等价物?或者其中一个比其他的更受欢迎?如果是这样的话?
cursor.execute("SELECT id, name FROM `table`")
for i in xrange(cursor.rowcount):
id, name = cursor.fetchone()
print id, name
cursor.execute("SELECT id, name FROM `table`")
result = cursor.fetchmany()
while result:
for id, name in result:
print id, name
result = cursor.fetchmany()
cursor.execute("SELECT id, name FROM `table`")
for id, name in cursor.fetchall():
print id, name
Run Code Online (Sandbox Code Playgroud) 从谁写ASYNCIO代码,但正在寻求更好地理解内部工作的人的角度来看,是什么yield from,await以及如何允许异步代码这些有用吗?
有一个高度赞成的问题询问yield from语法的用法和解释异步和等待的问题,但两者都深入讨论了不同的主题,并不是对底层代码及其如何适应asyncio的简明解释.
我的理解yield from是,它类似于yield从可迭代对象中获取每个项目。然而,我在以下示例中观察到不同的行为。
我有Class1
class Class1:
def __init__(self, gen):
self.gen = gen
def __iter__(self):
for el in self.gen:
yield el
Run Code Online (Sandbox Code Playgroud)
和 Class2 的不同之处仅在于yield将 for 循环替换为yield from
class Class2:
def __init__(self, gen):
self.gen = gen
def __iter__(self):
yield from self.gen
Run Code Online (Sandbox Code Playgroud)
下面的代码从给定类的实例中读取第一个元素,然后在 for 循环中读取其余元素:
a = Class1((i for i in range(3)))
print(next(iter(a)))
for el in iter(a):
print(el)
Run Code Online (Sandbox Code Playgroud)
Class1这会为和产生不同的输出Class2。对于Class1输出是
0
1
2
Run Code Online (Sandbox Code Playgroud)
Class2输出为
0
Run Code Online (Sandbox Code Playgroud)
yield from产生不同行为的背后机制是什么?
python 3.3.2+ python支持创建生成器函数的新语法
yield from <expression>
Run Code Online (Sandbox Code Playgroud)
我已经快速尝试了这个
>>> def g():
... yield from [1,2,3,4]
...
>>> for i in g():
... print(i)
...
1
2
3
4
>>>
Run Code Online (Sandbox Code Playgroud)
它似乎很简单,但PEP文件很复杂.我的问题是,与之前的收益率声明相比,还有其他区别吗?谢谢.
我正在尝试从具有784位长行的CSV文件创建数据集。这是我的代码:
import tensorflow as tf
f = open("test.csv", "r")
csvreader = csv.reader(f)
gen = (row for row in csvreader)
ds = tf.data.Dataset()
ds.from_generator(gen, [tf.uint8]*28**2)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-22-4b244ea66c1d> in <module>()
12 gen = (row for row in csvreader_pat_trn)
13 ds = tf.data.Dataset()
---> 14 ds.from_generator(gen, [tf.uint8]*28**2)
~/Documents/Programming/ANN/labs/lib/python3.6/site-packages/tensorflow/python/data/ops/dataset_ops.py in from_generator(generator, output_types, output_shapes)
317 """
318 if not callable(generator):
--> 319 raise TypeError("`generator` must be callable.")
320 if output_shapes is None:
321 output_shapes = nest.map_structure(
TypeError: `generator` …Run Code Online (Sandbox Code Playgroud) C#程序员试图学习一些Python。我正在尝试运行CPU密集型计算,同时让IO绑定的异步方法在后台悄悄切换。在C#中,我通常会设置等待的时间,然后启动CPU密集型代码,然后等待IO任务,然后合并结果。
这是我在C#中的做法
static async Task DoStuff() {
var ioBoundTask = DoIoBoundWorkAsync();
int cpuBoundResult = DoCpuIntensizeCalc();
int ioBoundResult = await ioBoundTask.ConfigureAwait(false);
Console.WriteLine($"The result is {cpuBoundResult + ioBoundResult}");
}
static async Task<int> DoIoBoundWorkAsync() {
Console.WriteLine("Make API call...");
await Task.Delay(2500).ConfigureAwait(false); // non-blocking async call
Console.WriteLine("Data back.");
return 1;
}
static int DoCpuIntensizeCalc() {
Console.WriteLine("Do smart calc...");
Thread.Sleep(2000); // blocking call. e.g. a spinning loop
Console.WriteLine("Calc finished.");
return 2;
}
Run Code Online (Sandbox Code Playgroud)
这是python中的等效代码
static async Task DoStuff() {
var ioBoundTask = DoIoBoundWorkAsync();
int cpuBoundResult = DoCpuIntensizeCalc(); …Run Code Online (Sandbox Code Playgroud) 如何从 pytest 测试模块向正在运行的 pygame 注入事件?
以下是一个 pygame 的最小示例,它在J按下时绘制一个白色矩形并在按下时退出游戏Ctrl-Q。
#!/usr/bin/env python
"""minimal_pygame.py"""
import pygame
def minimal_pygame(testing: bool=False):
pygame.init()
game_window_sf = pygame.display.set_mode(
size=(400, 300),
)
pygame.display.flip()
game_running = True
while game_running:
# Main game loop:
# the following hook to inject events from pytest does not work:
# if testing:
# test_input = (yield)
# pygame.event.post(test_input)
for event in pygame.event.get():
# React to closing the pygame window:
if event.type == pygame.QUIT:
game_running = False
break
# React to …Run Code Online (Sandbox Code Playgroud) 我想将JSON树结构的每个分支转换为该分支中的项列表.我想用循环来做,但我无法使用索引访问对象.
Example JSON:
{
"Root": { "child1": "abc",
"child2": "def",
"child3": { "grandchild1": "nick",
"grandchild2": "Sam"
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想遍历它们并将它们存储如下:
list1 = ['Root', "child1", "abc"]
list2 = ['Root', "child2", "def"]
list3 = ['Root', "child3", "grandchild1", "nick",]
list4 = ['Root', "child3", "grandchild2", "sam",]
Run Code Online (Sandbox Code Playgroud)
我读了JSON如下:
import json
with open('sample.json') as f:
tree = json.load(f)
Run Code Online (Sandbox Code Playgroud)
问题:
我想循环遍历这些项目并将其附加到各种列表但我只能通过他们的密钥访问它们,就像tree['Root']给予Child1,2,3,然后tree['Root']['child3']应该给我另外两个成员.但是,在我的用例中,此方法不可伸缩,我在JSON文件中有1400个分支(非常深嵌套),我想为它们创建1400个列表.
任何想法如何有效地做到这一点?
我会这样做:
def walk(samples):
for d in range(samples):
yield d
def walk200():
for d in walk(200):
yield d
Run Code Online (Sandbox Code Playgroud)
但实际上我想要的是这个,使代码更短:
def walk200():
reyield walk(200)
Run Code Online (Sandbox Code Playgroud)
我该怎么办reyield?
在我的单元测试中,我有两个非常相似的装置,我希望将某些功能分解为某种辅助函数。鉴于我对如何yield生成生成器的理解,我认为这不会导致任何问题。my_fixture_with_helper, 应该只返回 `fixture_helper 产生的生成器。
import pytest
def fixture_helper():
print("Initialized from the helper...")
yield 26
print("Tearing down after the helper...")
@pytest.fixture
def my_fixture_with_helper():
return fixture_helper()
@pytest.fixture
def my_fixture():
print("Initialized from the fixture...")
yield 26
print("Tearing down after the fixture...")
def test_nohelper(my_fixture):
pass
def test_helper(my_fixture_with_helper):
pass
Run Code Online (Sandbox Code Playgroud)
但是,如果我运行pytest --capture=no,我会得到以下信息
test_foo.py Initialized from the fixture...
.Tearing down after the fixture...
.
Run Code Online (Sandbox Code Playgroud)
我希望“从帮手初始化”和“在帮手之后拆解”得到打印,但事实并非如此,我不知道为什么。为什么这不起作用?
假设我在 F# 中有以下代码:
let rec all_numbers_from k =
yield k
yield! all_numbers_from (k+1)
Run Code Online (Sandbox Code Playgroud)
这段代码可以称为all_numbers_from 0,生成从 0 到无穷大的所有数字。我知道 Python 也有一个yield关键字,它的行为似乎与 F# 的yield运算符非常相似。我的问题是是否还有某种等效于 F# 的yield!运算符?
python ×11
generator ×3
async-await ×2
pytest ×2
python-3.x ×2
yield ×2
algorithm ×1
coroutine ×1
json ×1
mysql ×1
pygame ×1
recursion ×1
yield-from ×1