Files
2012-12-30 14:55:16 +08:00

75 lines
2.1 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
Content-Type: text/x-zim-wiki
Wiki-Format: zim 0.4
Creation-Date: 2012-10-04T13:47:32+08:00
====== unpack ======
Created Thursday 04 October 2012
>>> for k,v in ["fdf",23,"dfdf",33]:
... print k,v
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: __too many__ values to unpack
顺序容器类型如str, list, tuple__每次迭代时只能返回其中的一个元素__。
所以第一次返回循环返回**"fdf"**,但是它有三个元素最多只能赋值给两个
变量。
>>> for k,v in "dfdf":
... print k,v
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: __need more than 1 value__ to unpack
字符串迭代时每次返回其中的一个字符。所以最多只能unpack给一个变量。
>>> k,v="dfdf"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: __too many values to unpack__
unpack一个顺序容器类型时左边变量的数目必须要与容器中元素的个数相同。
>>> k,v="df"
>>> print k,v
d f
>>>
In [9]: for k,v in 'dfdf': //对于字符串的迭代迭代其每次只返回__一个字符__所以赋值给k,v时出错
...: print k,v
...:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-9-5ba17a6181e2> in <module>()
----> 1 for k,v in 'dfdf':
2 print k,v
3
ValueError: need more than 1 value to unpack
In [10]: k,v='ff' __//对于可迭代对象展开后的元素个数必须与等式左边的相等。__
In [11]: print k,v
**f f**
In [13]: k,v='fff'
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-0aecd2a10b05> in <module>()
----> 1 k,v='fff'
ValueError: too many values to unpack
In [14]:
In [12]:
In [12]: for k,v in ['df',[1,2],(3,4)]: __//每次迭代器返回列表中的一个元素每个元素都可以展开为2个变量。__
print k,v
....:
d f
1 2
3 4
In [13]: