本文介绍了在迭代中无需复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我正盯着今天看起来像这样的一段代码:


for stuff in stuff [x :y]:

无论什么(东西)


并且想知道编译器是否真的从

制作了切片的副本代码似乎建议的东西,或者它是否找到了一些生成

迭代器的方法而无需复制(如果内容是内置的

序列类型)?或者更笨拙更有效率(在我的意见中,我的意见):

$ x $ b for x in xrange(x,y):

无论如何(东西[i])


詹姆斯

Hello all,

I was staring at a segment of code that looked like this today:

for something in stuff[x:y]:
whatever(something)

and was wondering if the compiler really made a copy of the slice from
stuff as the code seems to suggest, or does it find some way to produce
an iterator without the need to make a copy (if stuff is a built-in
sequence type)? Or would it be more efficient to do the more clumsy (in
my opinion):

for i in xrange(x, y):
whatever(stuff[i])

James

推荐答案



itertools.islice做你想要的事情


导入itertools

用于itertools.islice中的东西(stuff,x,y):

无论什么(东西)

itertools.islice does what you want

import itertools
for something in itertools.islice(stuff, x, y):
whatever(something)




itertools.islice做你想做的事


import itertools

for itertools.islice(stuff,x,y):

无论什么(东西)


itertools.islice does what you want

import itertools
for something in itertools.islice(stuff, x, y):
whatever(something)



谢谢buffi!


所以我猜解释器后者没有优化?


James

Thanks buffi!

So I guess the interpreter does no optimization in the latter?

James




谢谢buffi!


所以我想解释器在后者中没有优化?


詹姆斯


Thanks buffi!

So I guess the interpreter does no optimization in the latter?

James



不,据我所知,当你这样做时,它会从切片中创建一个新列表

喜欢

的东西[x:y]


- Bj?rnKempén

No, as far as I know it makes a new list out of the slice when you do
it like
for something in stuff[x:y]

- Bj?rn Kempén


这篇关于在迭代中无需复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:22