生成器到列表的python切片分配 [英] python slice assignment of generator to list

查看:51
本文介绍了生成器到列表的python切片分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

my_list = [1, 2]

def f():
    print my_list
    yield 11
    print my_list
    yield 22
    print my_list

my_list[:] = f()

print "finally ",
print my_list

输出:

[1, 2]
[1, 2]
[1, 2]
finally  [11, 22]

我期望的是:

[1, 2]
[11, 2]
[11, 22]
finally [11, 22]

有人曾经告诉我切片分配已经到位.很明显不是.是否有一种优雅的方法来实现它?

Someone once told me slice assignment was in place. Obviously not. Is there an elegant way to achieve it?

推荐答案

Slice分配是就地的,但是直到消耗完整个生成器之后,该分配才会发生.它不会一次为列表分配一个元素.它会读取所有内容,然后一次性将它们全部粘贴到列表中.

Slice assignment is in-place, but the assignment doesn't happen until the entire generator is consumed. It doesn't assign one element at a time to the list. It reads them all and then sticks them all into the list at once.

(请注意,它必须这样做,因为即使序列的长度与原始切片的长度不同,也可以将序列分配给切片.您可以这样做,例如 x [2:3]= [1、2、3、4、5、6] .无法通过一次替换一个元素来做到这一点,因为在旧切片和新序列之间没有一对一的映射取代它.)

(Note that it has to do it this way because you can assign a sequence to a slice even if the sequence is a different length than the original slice. You can do, e.g., x[2:3] = [1, 2, 3, 4, 5, 6]. There's no way to do this by replacing one element at a time, because there's no one-to-one mapping between the old slice and the new sequence that's replacing it.)

没有一种方法可以通过切片分配来实现所需的功能,因为切片分配始终以这种一次性的方式工作.您将不得不并行遍历列表和生成器,并一次替换一个元素.

There isn't a way to achieve what you want by slice assignment, because slice assignment always works in this all-at-once way. You would have to iterate over the list and the generator in parallel and replace individual elements one at a time.

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

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