在 python 中,當使用 for 回圈進行迭代時,我們何時使用for x in y與 for x,y in z。
我的猜測是它取決于迭代,如果是這樣,你能向我解釋一下一般約定嗎?
即當您使用列舉函式時,它是for x,y, in z.
謝謝大家
uj5u.com熱心網友回復:
您通常為 , 的左側提供模式in,以從可迭代中捕獲結構。
迭代names = ['joe', 'chloe', 'karen']是你已經知道的。
但是您可以捕獲任意數量的線性值。
>>> res = [['joe',1,2], ['chloe',2,3]]
>>> for name, tag1, tag2 in res:
... print(name, tag1, tag2)
...
joe 1 2
chloe 2 3
或者,
>>> res = [['joe', 1,2,3], ['chloe', 3,4]]
>>> for name, first, *rest in res:
... print(name, first, rest)
...
joe 1 [2, 3]
chloe 3 [4]
解壓字典與串列相同。
>>> tps = [('adam', 31, {'a': '1', 'b': 2}), ('karen', 21, {'b': 3, 'a': 9})]
>>> for name, age, keys in tps:
... print(name, age, keys['a'])
...
adam 31 1
karen 21 9
>>> for name, age, keys in tps:
... print(name, age, [k for k in keys]) #nested for loop
...
adam 31 ['a', 'b']
karen 21 ['b', 'a']
>>> for name, age, *keys in tps: # * puts result in [] container
... print(name, age, [k for k in keys])
...
adam 31 [{'a': '1', 'b': 2}]
karen 21 [{'b': 3, 'a': 9}]
列舉物件
| The enumerate object yields pairs containing a count (from start, which
| defaults to zero) and a value yielded by the iterable argument.
|
| enumerate is useful for obtaining an indexed list:
| (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
因此,可以解壓縮enumerate(ys)為x, y其中 x 是 ys 集合中 y 的索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/493676.html
