對不起,問一個愚蠢的問題的聲明多個參數,但也有人告訴我下面的手段Python的語義 - 在for循環
for ctype, (codename, name) in searched_perms:
我不明白這是怎麼回事括號。 for ctype in serached_perms:
會很有意義。
我意識到答案是在python文檔的某處,但因爲我不知道我在找什麼,所以很難找到解釋。
對不起,問一個愚蠢的問題的聲明多個參數,但也有人告訴我下面的手段Python的語義 - 在for循環
for ctype, (codename, name) in searched_perms:
我不明白這是怎麼回事括號。 for ctype in serached_perms:
會很有意義。
我意識到答案是在python文檔的某處,但因爲我不知道我在找什麼,所以很難找到解釋。
ctype, (codename, name)
是一回事(ctype, (codename, name))
。因此,searched_perms
需要是形式(a,(b,c))的一系列事物,並且在每次循環迭代時,變量ctype
,codename
,name
將被設置爲a,b,c。
這實際上等效於
for x in search_perms:
ctype, y = x
codename, name = y
或
for x in search_perms:
ctype = x[0]
codename = x[1][0]
name = x[1][1]
即,它從解壓縮的search_perms
的項目,如對,然後解包每對爲一對的第二項爲好。
實施例:
>>> d = {"ham": "yes", "spam": "no", "eggs": "please"}
>>> for k, v in d.iteritems():
... print("%s? %s" % (k, v))
...
eggs? please
ham? yes
spam? no
>>> for i, (k, v) in enumerate(d.iteritems()):
... print("question %d: %s? %s" % (i, k, v))
...
question 0: eggs? please
question 1: ham? yes
question 2: spam? no
此操作,因爲生成enumerate(d.iteritems())
對,其中每一個第二元件再次是一對:
>>> list(enumerate(d.iteritems()))
[(0, ('eggs', 'please')), (1, ('ham', 'yes')), (2, ('spam', 'no'))]
這意味着searched_perms
是一個迭代器,在迭代期間返回兩個元素:第一個是ctype
,第二個是元組,由另外兩個元素組成:(codename, name)
。所以searched_perms
看起來是這樣的:
[[ctype1, (code1, name1)], [ctype2, (code2, name2)], ...]
語法for ctype, (codename, name) in searched_perms
允許的所有內容提取的searched_perms
,逐個元素。
你的列表searchedparams
應該看起來是這樣的:
In [1]: L = []
In [2]: L.append(('a', ('b', 'c')))
In [3]: L.append(('d', ('e', 'f')))
In [4]: L
Out[4]: [('a', ('b', 'c')), ('d', ('e', 'f'))]
In [6]: for ctype, (codename, name) in L:
print ctype, codename, name
...:
a b c
d e f
('a', ('b', 'c'))
是2個值,其中權值也是兩個值的元組的元組。
[Tuple unpacking](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences)。 –