将迭代器分配给Python切片 [英] Assign iterators to a Python slice

查看:42
本文介绍了将迭代器分配给Python切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Python分配给切片之前,是否消耗了迭代器?分配前消耗"是指在切片分配发生之前,所有元素都同时在内存中创建(放入列表或元组).另一种方法是将迭代器中的元素逐一放入切片中,这样就不会同时在内存中创建元素.

Are iterators consumed before being assigned to a slice in Python? By "consumed before being assigned" I mean the elements are created in the memory all at the same time (put into list or tuple) before the slice assignment happens. The other approach would be to put the elements from the iterator in the slice one-by-one, so elements are not created in the memory all at the same time.

例如,让我们考虑以下代码:

For example, let`s consider this code:

from itertools import islice
from heapq import merge

c = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5] + list(range(10))
lo, mid, hi = 0, 10, 20
c[lo:hi] = merge(islice(iter(c), lo, mid), islice(iter(c), mid, hi))

merge返回一个迭代器,该迭代器选择两个要合并的迭代器中的最小元素.在切片分配发生之前会消耗掉这些迭代器吗?

merge returns an iterator that picks the smallest element of the two iterators given to merge. Would these iterator be consumed before the slice assignment happens?

推荐答案

这取决于切片分配到的序列的实现.序列直接接收迭代器,使用迭代器的详细信息取决于序列.

This depends on the implementation of the sequence that is being slice-assigned into. The sequence receives the iterator directly, and the details of consuming the iterator are up to the sequence.

对于列表,当前CPython实现消耗了对该列表进行任何修改之前先进行迭代:

For lists, the current CPython implementation consumes the iterator up front before any modification to the list:

v_as_SF = PySequence_Fast(v, "can only assign an iterable");

PySequence_Fast 将从尚未包含列表或元组的任何参数中构建列表.

PySequence_Fast will build a list out of any argument that isn't already a list or tuple.

还有自我分配处理,因为在将列表切片分配给自身时,将输入转换为列表还不够安全:

There's also self-assignment handling, because turning the input into a list isn't enough to be safe when you're slice-assigning a list into itself:

/* Special case "a[i:j] = a" -- copy b first */
v = list_slice(b, 0, Py_SIZE(b));

我认为没有任何有关此列表行为的记录.

I don't think any of this list behavior is documented.

这篇关于将迭代器分配给Python切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆