For 循环语法约定

问题描述 投票:0回答:1

在 python 中,当使用 for 循环进行迭代时,我们何时使用

for x in y
与 for
x,y in z

我的猜测是它取决于可迭代,如果是这样,你能给我解释一下一般约定吗?

即当您使用枚举函数时,它是

for x,y, in z

谢谢大家

python for-loop iteration
1个回答
0
投票

要从可迭代中捕获结构,您需要在

for
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 是 y 在 ys 集合中的索引。

© www.soinside.com 2019 - 2024. All rights reserved.