嘗試這樣:
>>> lis=(1,)[:2] #just one value,
>>> lis
(1,)
>>> lis=(1,2)[:2] #two values
>>> lis
(1, 2)
>>> lis=(1,2,3,4,5)[:2] #any number of values
>>> lis
(1, 2)
# used [:2] here, because you only expect a maximum of 2 values
# use [:] to collect any number of values
但是這種方法唯一的問題是,你需要在每一個return
語句返回tuple
, 所以return False
使用iter()
成爲return False,
,這也期望你總是返回一個元組或任何可迭代的:
>>> ret=((1,))
>>> ret=iter((1,))
>>> a,b=ret.next(),list(ret)[:1] #used [:1] coz we need to store only 2 elements
>>> a,b
(1, [])
>>> ret=iter((1,2))
>>> a,b=ret.next(),list(ret)[:1]
>>> a,b
(1, [2])
>>> ret=iter((1,2,3,4))
>>> a,b=ret.next(),list(ret)[:1]
>>> a,b
(1, [2])
python version? –
我正在使用Python 2.7.3。 – user1447941