WordPress网站建设宣传图片

Python for循环同时遍历两个列表

释放双眼,带上耳机,听听看~!

Python for循环同时遍历两个列表我们可以使用Python zip函数来实现,

zip() 函数简介

zip() 函数是 Python 内置函数之一,zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成zip对象。

在Python2中,zip() 函数返回的是列表,在Python3中,则是返回上述所说的zip对象,这样可以减少内存。如果需要列表,我们可以使用list()转换为列表。不过它们包含的元素都是一样的(都是元组)。

语法

zip([iterable, …])

参数说明:

  • iterable — 一个或多个迭代器;

for循环同时遍历两个列表示例代码

# -*- coding: utf-8 -*-
odd_number_list = [1, 3, 5, 7, 9]
even_number_list = [2, 4, 6, 8, 10]
for number in zip(odd_number_list, even_number_list):
    print(number)
print('---' * 10)
for odd_number, even_number in zip(odd_number_list, even_number_list):
    print(odd_number, even_number)

输出结果

(1, 2)
(3, 4)
(5, 6)
(7, 8)
(9, 10)
------------------------------
1 2
3 4
5 6
7 8
9 10

注意事项

迭代器的元素个数不一致会怎样?

如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。

在网上还看到其他的回答内容说在Python2中,如果你需要遍历大数据量的迭代器时,使用zip函数可能会占用大量的内存,这个时候建议使用itertools模块中的izip函数,

itertools.izip(*iterables)用于将多个可迭代对象对应位置的元素作为一个元组,将所有元组『组成』一个迭代器,并返回,不过这个函数在python3.x中已不存,Python3中我们直接使用zip即可。

如果两个列表(迭代器)的长度不一,在Python2中可以使用itertools模块的izip_longest函数(该函数在python3.x中已不存在),izip_longest跟 izip 类似,但izip_longest在迭代过程会持续到所有可迭代对象的元素都被迭代完。

izip_longest 示例代码

from itertools import izip_longest
for item in izip_longest([1, 2, 3], ['a', 'b', 'c', 'd', 'e'],fillvalue='-'):
    print(item)

输出结果

(1, 'a')
(2, 'b')
(3, 'c')
('-','d')
('-','e')

既然izip_longest函数在Python3中已不存在,那么在Python3中想要遍历完最长的对象应该怎样呢?在Python中可以使用itertools中的zip_longest函数:

zip_longest 示例代码

from itertools import zip_longest

for item in zip_longest([1, 2, 3], ['a', 'b', 'c', 'd', 'e']):
    print(item)

输出结果

(1, 'a')
(2, 'b')
(3, 'c')
(None, 'd')
(None, 'e')

缺失值我们可以使用fillvalue参数去设置:

from itertools import zip_longest

for item in zip_longest([1, 2, 3], ['a', 'b', 'c', 'd', 'e'], fillvalue='-'):
    print(item)

输出结果

(1, 'a')
(2, 'b')
(3, 'c')
('-', 'd')
('-', 'e')

其他方式实现

除了zip函数,还可以使用先用len函数的方式得到一个列表的长度,然后循环这个长度数字,根据这个数字作为列表的索引去对两个列表取值,不过这种方法显然不如zip简单快捷…

Python列表相关文章

Python enumerate() 函数,Python将列表转换为索引:元素的字典

python sort()函数详解 – python列表排序函数

Python for 循环列表每次取值指定个数元素

Python从列表中随机获取元素方法

Python获取两个列表的交集

相关资料

2. Built-in Functions—Python 2.7.18 documentation – zip([iterable, …])

itertools — Functions creating iterators for efficient looping — Python 3.12.2 documentation – itertools.zip_longest(*iterables, fillvalue=None)

给TA打赏
共{{data.count}}人
人已打赏
Python列表Python笔记

Python for 循环列表每次取值指定个数元素

2024-4-7 17:53:11

Python与SEOPython笔记

使用Python批量检查网站友情链接

2024-4-12 21:48:07

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索
展开目录