Python中一个for循环循环多个变量的示例

yipeiwu_com6年前Python基础

首先,熟悉一个函数zip,如下是使用help(zip)对zip的解释。

Help on built-in function zip in module __builtin__:

zip(...)

zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

Return a list of tuples, where each tuple contains the i-th element
from each of the argument sequences. The returned list is truncated
in length to the length of the shortest argument sequence.

看一个实例:

x = [1, 2, 3]
y = [-1, -2, -3] # y = [i * -1 for i in x]
zip(x, y)

zip的结果如下:

 [(1, -1), (2, -2), (3, -3)]

zip([seql, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。

进入正题:如何使用一个for循环同时循环多个变量呢?使用tuple。如下,同时循环i和j变量。

for (i, j) in [(1, 2), (2, 3), (4, 5)]:
print(i, j)

输出结果如下:

(1, 2)
(2, 3)
(4, 5)

所以我们如果要将x和y中的元素分别相加,则可以使用如下代码:

for (i, j) in zip(x, y):
  print(i + j)

输出结果:

0
0
0

以上这篇Python中一个for循环循环多个变量的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

让python同时兼容python2和python3的8个技巧分享

python邮件列表里有人发表言论说“python3在10内都无法普及”。在我看来这样的观点有些过于悲观,python3和python2虽然不兼容,但他们之间差别并没很多人想像的那么大。...

python3+opencv3识别图片中的物体并截取的方法

如下所示: 运行环境:python3.6.4 opencv3.4.0 # -*- coding:utf-8 -*- """ Note: 使用Python和OpenCV检测...

pycharm 使用心得(九)解决No Python interpreter selected的问题

pycharm 使用心得(九)解决No Python interpreter selected的问题

初次安装完PyCharm后,新建项目时,遇到了No Python interpreter selected的问题。 意思是说没有找到Python解释器。那我们添加Python解释器即可...

PyQt5 QTableView设置某一列不可编辑的方法

如下所示: class EmptyDelegate(QItemDelegate): def __init__(self,parent): super(EmptyDeleg...

python3 图片 4通道转成3通道 1通道转成3通道 图片压缩实例

我就废话不多说了,直接上代码吧! from PIL import Image # 通道转换 def change_image_channels(image, image_path):...