元组赋值和生成器? [英] Tuple assignment and generators?

查看:80
本文介绍了元组赋值和生成器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个迂腐的练习来尝试理解Python一个更好的,我决定尝试制作一个发电机或类

,这将允许我解压缩任意数量的

可计算值。在这种情况下,只是零(虽然我只是为了证明任何最终工作,有一个计数

发电机将是不错的)。目标语法是

类似

a,b,c = 0 ()
q,r,s,t,u,v =零()


其中zeros()返回一个适当大小的元组/

零列表。


我尝试了一些谷歌搜索,但我的所有尝试都只是

最终指向那些blithly描述元组的页面

赋值,而不是在这个过程中对

对象调用什么方法的细节。


我的第一个想法是让它使用发电机:


def zeros():

而1:收益0


但是,我得到了一个ValueError:太多的值来

unpack结果。


作为第二次尝试,我在课堂上尝试了几次尝试

(我开始使用以下示例类,只是派生了

来自object而不是list,但它没有任何

更好的运气):

class zeros(list):
.... def __getitem __(self,i):

....返回0

.... z =零()
a,b,c = z



回溯(最近一次调用最后一次):

文件"< stdin> ;",第1行,在?

ValueError:需要超过0的值来解包

看起来我需要有一个预先定义的长度,但我' '

无法确定需要采取什么样的措施

被覆盖。好像我需要一个


def __len __(自我):

返回INFINITY


所以它没有不要呛到它。然而,如何将

解释器变成真正相信该对象具有所需元素的元素正在逃避我。或者,如果有
,则doYouHaveThisManyElements被称为伪b函数的伪函数,我可以撒谎并且总是返回true。


任何关于我缺少的提示?


谢谢,


-tkc

解决方案

< blockquote> Tim Chase写道:

作为一个试图理解Python的迂腐练习,我决定尝试制作一个发电机或类。
这将允许我解压缩任意数量的可计算值。在这种情况下,只是零(虽然我只是为了证明任何最终工作,有一个计数
生成器将是不错的)。目标语法是
类似




< snip />


使用这个:<

http://aspn.activestate .com / ASPN / Coo ... / Recipe / 284742

我想出了一个小装饰师这样做:


import inspect, dis b / b

def expecting():

"""返回调用者期望的值""

f = inspect.currentframe()

f = f.f_back.f_back

c = f.f_code

i = f.f_lasti
bytecode = c.co_code

instruction = ord(bytecode [i + 3])

if instruction == dis.opmap [''UNPACK_SEQUENCE'' ]:

howmany = ord(字节码[i + 4])

返回howmany

elif指令== dis.opmap [''POP_TOP '']:

返回0

返回1


def variably_unpack(f):

def d(* args,** kwargs):

r = f(* args,** kwargs)

exp = expecting()

如果exp< 2:

返回exp

return(r.next()for x in xrange(exp))

return d
< br $>
@variably_unpack

def test():

def gen():

i = 0

而True:

收益率我

i + = 1

返回gen()


a,b,c = test()


打印a,b,c

a,b,c,d = test()


打印a,b,c,d


Diez



Tim Chase写道:

作为一个迂腐的练习,试图更好地理解Python,我决定尝试制作一个允许我使用的生成器或类
解压缩任意数量的可计算值。在这种情况下,只是零(虽然我只是为了证明任何最终起作用,有一个
计数发生器会很好)。目标语法将是

a,b,c = zeros()
q,r,s, t,u,v = zeros()
其中" zeros()"返回一个适当大小的元组/零列表。

我已经尝试了一些谷歌搜索,但我所有的尝试刚刚结束
指向blithly描述元组赋值的页面,而不是
详细说明了在过程中对象调用的方法。

我的第一个想法是让它使用生成器:

def zeros() :
1:yield 0

然而,我得到了一个ValueError:太多的值来解包结果。

作为第二次尝试,我尝试了几次类的尝试(我开始使用以下示例类,仅从object而不是
派生。 ;列表",但它没有更好的运气):
class zeros(list):... def __getitem __(self,i):
...返回0
... z = zeros()
a,b,c = z


Traceback(最近一次调用最后一次):
文件"< stdin> ",第1行,在?
ValueError:需要超过0的值才能解包

看起来我需要预定义的长度,但我有
def __len __(自我):
返回INFINITY

所以它并没有因此而窒息。但是,如何将翻译人员欺骗,确实相信对象具有所需的元素正在逃避我。或者,如果有一个叫做doYouHaveThisManyElements的伪函数,我可以撒谎并且总是返回true。

任何关于我缺少的东西的提示?

谢谢,

-tkc



虽然我在5年的Python中从未需要这样的东西

编程,这是一种方式:


a,b,c = 3 * [0]

q,r,s,t,u, v = 6 * [0]


如果您愿意:


def zeros(num):

返回num * [0]


a,b,c =零(3)

q,r,s,t,u,v =零(6)


我认为我不是每次都使用这样的原因就是

你不需要将Python中的变量初始化为零和我会

可能使用一个列表而不是像q,r,s,t,u,v这样的个别变量。


-Larry Bates


我不认为他明确想要将事物初始化为零,

而是将任意序列解压缩到一个元组中(例如,可能是

斐波纳西序列)。



def zeros(count):
.... for i in range(count ):

....收益率0

.... a,b,c =零(3)
a
0 b
0 c



0


Just as a pedantic exercise to try and understand Python a
bit better, I decided to try to make a generator or class
that would allow me to unpack an arbitrary number of
calculatible values. In this case, just zeros (though I
just to prove whatever ends up working, having a counting
generator would be nice). The target syntax would be
something like

a,b,c = zeros()
q,r,s,t,u,v = zeros()
where "zeros()" returns an appropriately sized tuple/list of
zeros.

I''ve tried a bit of googling, but all my attempts have just
ended up pointing to pages that blithly describe tuple
assignment, not the details of what methods are called on an
object in the process.

My first thought was to get it to use a generator:

def zeros():
while 1: yield 0

However, I get back a "ValueError: too many values to
unpack" result.

As a second attempt, I tried a couple of attempts at classes
(I started with the following example class, only derived
from "object" rather than "list", but it didn''t have any
better luck):
class zeros(list): .... def __getitem__(self,i):
.... return 0
.... z = zeros()
a,b,c = z


Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: need more than 0 values to unpack
It looks like I need to have a pre-defined length, but I''m
having trouble figuring out what sorts of things need to be
overridden. It seems like I sorta need a

def __len__(self):
return INFINITY

so it doesn''t choke on it. However, how to dupe the
interpreter into really believing that the object has the
desired elements is escaping me. Alternatively if there was
a "doYouHaveThisManyElements" pseudo-function that was
called, I could lie and always return true.

Any hints on what I''m missing?

Thanks,

-tkc


解决方案

Tim Chase wrote:

Just as a pedantic exercise to try and understand Python a
bit better, I decided to try to make a generator or class
that would allow me to unpack an arbitrary number of
calculatible values. In this case, just zeros (though I
just to prove whatever ends up working, having a counting
generator would be nice). The target syntax would be
something like



<snip/>

By using this:

http://aspn.activestate.com/ASPN/Coo.../Recipe/284742
I came up with a small decorator doing that:

import inspect, dis

def expecting():
"""Return how many values the caller is expecting"""
f = inspect.currentframe()
f = f.f_back.f_back
c = f.f_code
i = f.f_lasti
bytecode = c.co_code
instruction = ord(bytecode[i+3])
if instruction == dis.opmap[''UNPACK_SEQUENCE'']:
howmany = ord(bytecode[i+4])
return howmany
elif instruction == dis.opmap[''POP_TOP'']:
return 0
return 1

def variably_unpack(f):
def d(*args, **kwargs):
r = f(*args, **kwargs)
exp = expecting()
if exp < 2:
return exp
return (r.next() for i in xrange(exp))
return d

@variably_unpack
def test():
def gen():
i = 0
while True:
yield i
i += 1
return gen()

a, b, c = test()

print a,b,c

a, b, c, d = test()

print a,b,c, d

Diez



Tim Chase wrote:

Just as a pedantic exercise to try and understand Python a bit better, I
decided to try to make a generator or class that would allow me to
unpack an arbitrary number of calculatible values. In this case, just
zeros (though I just to prove whatever ends up working, having a
counting generator would be nice). The target syntax would be something
like

a,b,c = zeros()
q,r,s,t,u,v = zeros()
where "zeros()" returns an appropriately sized tuple/list of zeros.

I''ve tried a bit of googling, but all my attempts have just ended up
pointing to pages that blithly describe tuple assignment, not the
details of what methods are called on an object in the process.

My first thought was to get it to use a generator:

def zeros():
while 1: yield 0

However, I get back a "ValueError: too many values to unpack" result.

As a second attempt, I tried a couple of attempts at classes (I started
with the following example class, only derived from "object" rather than
"list", but it didn''t have any better luck):
class zeros(list): ... def __getitem__(self,i):
... return 0
... z = zeros()
a,b,c = z


Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: need more than 0 values to unpack
It looks like I need to have a pre-defined length, but I''m having
trouble figuring out what sorts of things need to be overridden. It
seems like I sorta need a

def __len__(self):
return INFINITY

so it doesn''t choke on it. However, how to dupe the interpreter into
really believing that the object has the desired elements is escaping
me. Alternatively if there was a "doYouHaveThisManyElements"
pseudo-function that was called, I could lie and always return true.

Any hints on what I''m missing?

Thanks,

-tkc


While I have never needed anything like this in my 5 years of Python
programming, here is a way:

a,b,c = 3*[0]
q,r,s,t,u,v = 6*[0]

of if you like:

def zeros(num):
return num*[0]

a,b,c = zeros(3)
q,r,s,t,u,v = zeros(6)

I think the reason I don''t every use anything like this is that
you don''t need to initialize variables in Python to zero and I would
probably use a list instead of individual variables like q,r,s,t,u,v.

-Larry Bates


I don''t think he was explicitly wanting to initialize things to zero,
but rather unpack an arbitrary sequence into a tuple (could perhaps be
the fibonnacci sequence for example).

How about:

def zeros(count): .... for i in range(count):
.... yield 0
.... a,b,c = zeros(3)
a 0 b 0 c


0


这篇关于元组赋值和生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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