标签: generator

如何创建迭代日期范围的 Python Generator 给我 3 天段?

我需要查询 API 以获取多月期间的数据。但是,API 的阻塞时间间隔超过 3 天。

所以我想创建一个生成器函数来将我的多月日期范围分成 3 天段,我可以在重复调用命中 API 的函数时使用这些段:当我传递开始日期和结束日期时,它给了我:

  • 第一次给我开始日期,开始日期+3天
  • 下次给我开始日期 + 3 天,开始日期 + 6 天
  • 此后每次向前移动 3 天
  • 直到它到达结束日期,如果我还有 1 或 2 天的数据要抓取,它会给我剩余的天数来达到结束日期
  • 停止

到目前为止,这是我的代码。它将第一次工作,但我不确定如何在下次调用该函数时使开始日期增加 3 天。而且我也不确定在达到最终结束日期之前我是否还有 1 或 2 天的时间来将我的until变量设置为最终结束日期——我认为现在它只是说“还有不到 3 天的时间,直到最后日期,所以让我们退出”:

3_day_segmenter(start, end):
    start_date = datetime.strptime(start, '%Y-%m-%d')
    end_date = datetime.strptime(end, '%Y-%m-%d')
    since = start_date
    for date in range(int ((end_date - start_date).days)): 
        until = start_date + datetime.timedelta(days=3)     
        yield since, until
Run Code Online (Sandbox Code Playgroud)

python date generator python-2.7

1
推荐指数
1
解决办法
4861
查看次数

使用生成器代替嵌套循环

我有以下嵌套循环。但在时间上效率低下。所以使用发电机会好得多。你知道怎么做吗?

x_sph[:] = [r*sin_t*cos_p for cos_p in cos_phi for sin_t in sin_theta for r in p]     
Run Code Online (Sandbox Code Playgroud)

似乎你们中的一些人认为(查看评论)在这种情况下使用生成器没有帮助。我的印象是使用生成器将避免将变量分配给内存,从而节省内存和时间。我错了吗?

python iteration generator nested-loops

1
推荐指数
1
解决办法
1235
查看次数

Python Generator 内存对大量读取的好处?

我想知道 python 生成器在这个用例中的内存优势(如果有的话)。我希望读入一个必须在所有对象之间共享的大文本文件。因为它只需要使用一次,一旦列表用完,程序就会结束,所以我打算使用生成器。

我相信生成器的“保存状态”可以让它跟踪下一个要传递给调用它的对象的值是什么。我读过生成器还可以通过不立即返回所有值而是即时计算它们来节省内存使用量。如果我在这个用例中得到任何好处,我有点困惑。

示例代码:

def bufferedFetch():
    while True:
        buffer = open("bigfile.txt","r").read().split('\n')
        for i in buffer:    
            yield i
Run Code Online (Sandbox Code Playgroud)

考虑到缓冲区无论如何都会读取整个“bigfile.txt”,这不会存储在生成器中,没有内存好处吗?有没有更好的方法来返回可以在所有对象之间共享的列表的下一个值?

谢谢。

python generator

1
推荐指数
1
解决办法
528
查看次数

有什么方法可以使发电机干燥吗?

下面的方法在我的课堂上,尝试在完成工作之前准备好自身。底漆懒于完成其后续的处理循环。在这两个循环中重复了五行,对于我来说,消除重复的最佳方法可能并不明显。

@classmethod
def __get_start_words(cls, iterable, n, start_words):
    iterator, buffer, sentinel = iter(iterable), Deque(maxlen=n), object()
    for _ in range(n):
        item = next(iterator, sentinel)
        if item is sentinel:
            # raise ValueError('iterable was too short to satisfy n')
            break
        buffer.append(item)
        yield item
    start_words[buffer.prefix] += 1
    while True:
        if buffer[0][-1] in cls.TERMINATORS:
            start_words[buffer.suffix] += 1
        item = next(iterator, sentinel)
        if item is sentinel:
            break
        buffer.append(item)
        yield item
Run Code Online (Sandbox Code Playgroud)

是否有一种有效且清晰的方法可以在类或方法中一次编写最后五行?


附录

在回答这个问题就什么prefix以及suffix是,这里是Deque类:

class Deque(collections.deque):
    """Deque([iterable[, maxlen]]) -> Deque instance"""

    @property …
Run Code Online (Sandbox Code Playgroud)

python iterator dry generator python-3.x

1
推荐指数
1
解决办法
93
查看次数

python生成器太慢而无法使用它.我为什么要用呢?什么时候?

最近我有问题,哪一个是其中最跑得最快的家伙iterator,list comprehension,iter(list comprehension)generator.然后制作如下的简单代码.

n = 1000000
iter_a = iter(range(n))
list_comp_a = [i for i in range(n)]
iter_list_comp_a = iter([i for i in range(n)])
gene_a = (i for i in range(n))

import time
import numpy as np

for xs in [iter_a, list_comp_a, iter_list_comp_a, gene_a]:
    start = time.time()
    np.sum(xs)
    end = time.time()
    print((end-start)*100)
Run Code Online (Sandbox Code Playgroud)

结果如下.

0.04439353942871094 # iterator
9.257078170776367 # list_comprehension
0.006318092346191406 # iterator of list_comprehension
7.491207122802734 # generator 
Run Code Online (Sandbox Code Playgroud)

发电机比其他东西慢.我不知道什么时候有用?

python performance list-comprehension generator

1
推荐指数
1
解决办法
2024
查看次数

如何在lisp中生成一个笛卡尔积?

这是我生成笛卡尔积的代码:

(defun cartesian-product (LIST)
  (LOOP FOR X IN LIST
    NCONC
        (LOOP FOR Y IN LIST
         COLLECT (LIST X Y))))
Run Code Online (Sandbox Code Playgroud)

我尝试输出其中一个笛卡儿产品:

(defun cartesian-product-generator (CALLBACK LIST)
  (LOOP FOR X IN LIST
    NCONC
        (LOOP FOR Y IN LIST
        DO(FUNCALL CALLBACK (LIST X Y)))))
Run Code Online (Sandbox Code Playgroud)

但是当我尝试使用以下测试时出现错误:

(cartesian-product-generator '(A B C))

Error: Too few arguments in call to #<Compiled-function cartesian-product-generator #x30200097E60F>:
       1 argument provided, at least 2 required.  While executing: cartesian-product-generator, in process listener(1).
Run Code Online (Sandbox Code Playgroud)

我是LISP的新手,想知道为什么会出现错误以及如何修复此错误.最终,我希望每次调用函数输出每个笛卡尔积.

例如,如果列表包含((1 1) (1 2) (2 1) (2 2)).我想生成(1 …

lisp loops generator common-lisp cartesian-product

1
推荐指数
1
解决办法
542
查看次数

python中的生成器错误

我仍然是python中的新生成器.我自己尝试了一个并尝试了一些非常简单的事情:

def fib(a):
...     if a==0 or a==1:return 1
...     yield fib(a-1)+fib(a-2)
print(list(fib(5))
Run Code Online (Sandbox Code Playgroud)

这段代码给了我这个错误:

TypeError: unsupported operand type(s) for +: 'generator' and 'generator'
Run Code Online (Sandbox Code Playgroud)

不能以这种方式使用发电机吗?

python generator fibonacci python-3.x

1
推荐指数
1
解决办法
480
查看次数

为什么javascript中的yield yield生成器的迭代次数错误?

所以这是我正在尝试使用的代码片段.

function* genBubble(arr) {
  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      yield arr; // returning arr after every iteration
      if (arr[j] > arr[j + 1]) {
        swap(arr, j, j + 1); // removed swap for brevity
      }
    }
  }
}
const tempArray = [3, 5, 8, 4, 1, 9, -2];
const genForLoop = genBubble(tempArray);

do {
  console.log(genForLoop.next());
} while (!genForLoop.next().done);
Run Code Online (Sandbox Code Playgroud)

这是一个简单的冒泡排序实现.如你所知,冒泡排序有 …

javascript iteration generator yield-keyword bubble-sort

1
推荐指数
1
解决办法
50
查看次数

如何以〜C速度排空异步发电机?

目前我正在使用 async for _ in asyncgen(): pass

我正在寻找“快速路由”实现,用于同步生成器的方法是:

deque(maxlen=0).extend(generator)
Run Code Online (Sandbox Code Playgroud)

python generator async-await python-asyncio

1
推荐指数
1
解决办法
107
查看次数

haskell-pointpoint两次捕获一个参数

该代码在Haskell中有效:

x a = (a + 1, a + 2)
x 2 -- returns (3, 4)
Run Code Online (Sandbox Code Playgroud)

而这不是:

x = ((+1), (+2))

<interactive>:935:1: error:
* Couldn't match expected type `Integer -> t'
              with actual type `(Integer -> Integer, Integer -> Integer)'
* The function `x' is applied to one argument,
  but its type `(Integer -> Integer, Integer -> Integer)' has none
  In the expression: x 2
  In an equation for `it': it = x 2
* Relevant bindings include it :: …
Run Code Online (Sandbox Code Playgroud)

haskell generator

1
推荐指数
2
解决办法
38
查看次数