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

yipeiwu_com7年前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中pip的使用和修改下载源的方法

基本命令 显示版本信息 pip -V 安装指定包 pip install <packages> pip install -i 'host' <package...

详解pandas删除缺失数据(pd.dropna()方法)

详解pandas删除缺失数据(pd.dropna()方法)

1.创建带有缺失值的数据库: import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5,...

打包python 加icon 去掉cmd黑窗口方法

如下所示: python pyinstaller.py -F -p C:\python27; -i .\xxx.ico .\demo.py --noconsole 以上这篇打包pytho...

Python里字典的基本用法(包括嵌套字典)

Python里字典的基本用法(包括嵌套字典)

Python字典的基本用法 创建字典: myDict1 = { '薛之谦':'我叫薛之谦', '吴青峰':'我叫吴青峰', '李宇春':'我叫李宇春', '花花':'...

将python2.7添加进64位系统的注册表方式

解决问题:python2.7无法在注册表中被识别,即在安装NumPy和SciPy等出现“python version 2.7 required, which was not found...