Python:使用zip函数从循环中提取一个迭代表达式 [英] Python : Extract one iteration expression from a loop with zip function

查看:37
本文介绍了Python:使用zip函数从循环中提取一个迭代表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python3中,我有以下循环:

In python3, I have the following loop :

for c,z in zip(ax.collections, [0.6, 0.8, 2, 0.7, 0.9, 2]):
  c.zorder = z

我不明白为什么单次迭代不正确:

I don't understand why a single iteration is not correct by doing :

ax.collections.zorder = [0.6, 0.8, 2, 0.7, 0.9, 2]

?

谁能解释一下为什么语法不正确?当然,这是由于 zip 函数所致.

Could anyone explain me why the syntax is not correct ? Surely this is due to the zip function.

推荐答案

ax.collections 是某种形式的可迭代对象,所涉及的 list 文字也是如此.zip 循环将 list 文字中的单个值分配给 ax.collections 中单个值的 zorder>. ax.collections 本身可能根本没有 zorder 属性,即使其中有,它的值也不会意识到.

ax.collections is an iterable of some form, as is the list literal involved. The zip loop is assigning a single value from the list literal to the zorder of a single value from ax.collections. ax.collections itself may not have a zorder attribute at all, and the values in it would not be aware of it even if it did.

要使单次迭代正确(假设 ax.collections 是一个序列,而不是任意迭代),您应该这样做:

To make a single iteration correct (assuming ax.collections is a sequence, rather than an arbitrary iterable), you'd do:

ax.collections[0].zorder = 0.6
# look up elem^^^          ^^^ assign single value to its attribute

ax.collections 本身未修改(仅其中一项),并且仅分配了 list 中的单个值.如果有助于理解,对于示例中的序列,可以认为 zip 的行为类似于此非Python的索引循环:

ax.collections itself is not modified (only an item in it), and only a single value from the list is assigned. If it helps understand it, for sequences in your example, zip can be considered to behave similarly to this unPythonic loop over indices:

mylist = [0.6, 0.8, 2, 0.7, 0.9, 2]
for i in range(min(len(ax.collections), len(mylist))):
    c = ax.collections[i]
    z = mylist[i]
    c.zorder = z

只是 zip 循环明显更快,并且适用于任何可迭代的,而不仅仅是可索引的序列(并且不需要输入具有名称,如上例中的索引所做的那样).

It's just that the zip loop is significantly faster, and works with any iterable, not just indexable sequences (and doesn't require the inputs to have names, as indexing does in the above example).

这篇关于Python:使用zip函数从循环中提取一个迭代表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆