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 数据加密代码

1、hashlib import hashlib #创建一个哈希对象 md = hashlib.md5() #md = hashlib.sha1() #md = hashlib.sha2...

创建Shapefile文件并写入数据的例子

创建Shapefile文件并写入数据的例子

基本思路 使用GDAL创建Shapefile数据的基本步骤如下: 使用osgeo.ogr.Driver的CreateDataSource()方法创建osgeo.ogr.DataSourc...

django表单的Widgets使用详解

前言 不要将Widget与表单的fields字段混淆。表单字段负责验证输入并直接在模板中使用。而Widget负责渲染网页上HTML表单的输入元素和提取提交的原始数据。widget是字段的...

python3安装pip3(install pip3 for python 3.x)

python3安装pip3(install pip3 for python 3.x)

前言:   我目前使用的服务器为centos6.x 系统自带的python的版本为2.6.x,但是目前无论是学习还是使用python,python3都是首选,那么问题来了。---如何安装...

Python如何实现动态数组

Python如何实现动态数组

Python序列类型 在本博客中,我们将学习探讨Python的各种“序列”类,内置的三大常用数据结构——列表类(list)、元组类(tuple)和字符串类(str)。 不知道你发现没有...