python同时遍历两个list用法说明
作者:s740556472 时间:2023-10-12 23:08:23
前言
需求是将两个list同时进行遍历,然后同步的将每个元素add到一个dict中,虽然有麻烦的方式,比如直接用list的数组下标可以实现,但是一点也不pythonic,于是想到了zip内置函数。记录下写法~
正文
废话不多说直接上代码:
dict_1 = {}
list_1 = ['a','b','c']
list_2 = ['1','2','3']
""" zip打包用法,同时遍历两个list """
for symbol,digit in zip(list_1,list_2):
dict_1[symbol] = digit
最终就是同步的将list1 、2进行遍历,同步的放入到dict中。
结果如下:
dict_1 = {'a':'1','b':'2','c':'3'}
补充知识:Python之for循环里面遍历两个List或多个对象
0、 * ,头回见这样的用法,其实in后面的两个list会组成(list1,list2)这样的元组,等于是target元组
def redirect_back(default='hello', **kwargs):
for target in request.args.get('next'), request.referrer:
if not target:
continue
if is_safe_url(target):
return redirect(target)
return redirect(url_for(default, **kwargs))
好变态的语法,我也是醉了,这样的方案也能解决我的bug
1、再看一个例子吧:
>>> for target in [1,2,3], [7,8,9]:
... print(target)
...
[1, 2, 3]
[7, 8, 9]
2、再来看一个,可见in后面当有多个对象的时候,会被组成一个tuple!!
每个target就是其中tuple中的一个元素哦
>>> for target in [1,2,3],["wangba",8,9],'hello':
... print(target)
...
[1, 2, 3]
['wangba', 8, 9]
hello
来源:https://blog.csdn.net/s740556472/article/details/82833078
标签:python,遍历,list
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python类继承用法实例分析
2022-01-25 16:44:13
Zend Framework生成验证码并实现验证码验证功能(附demo源码下载)
2024-05-03 15:13:30
Python操作Elasticsearch处理timeout超时
2022-04-23 02:42:18
![](https://img.aspxhome.com/file/2023/4/128584_0s.png)
python opencv设置摄像头分辨率以及各个参数的方法
2021-03-05 00:23:34
asp随机获取access数据库中的一条记录
2007-08-15 13:11:00
python中使用PIL制作并验证图片验证码
2023-06-05 11:28:33
利用php+mcDropdown实现文件路径可在下拉框选择
2023-09-11 15:18:02
百度的图片轮换JS代码,支持FF
2007-11-16 16:24:00
python爬取豆瓣评论制作词云代码
2023-03-14 04:31:40
![](https://img.aspxhome.com/file/2023/6/68286_0s.jpg)
用pandas中的DataFrame时选取行或列的方法
2023-05-15 07:43:04
基于python的列表list和集合set操作
2023-03-20 01:38:34
![](https://img.aspxhome.com/file/2023/6/111876_0s.jpg)
Python cookbook(数据结构与算法)让字典保持有序的方法
2022-04-28 03:28:04
php下常用表单验证的正则表达式
2024-05-03 15:35:08
JS异步函数队列功能实例分析
2024-04-22 13:26:28
python空值判断方式(if xxx和if xxx is None的区别及说明)
2022-04-01 20:18:42
动网论坛验证码改进 加法验证码(ASPJpeg版)
2011-04-10 10:44:00
![](https://img.aspxhome.com/file/UploadPic/20112/5/201125112026274s.gif)
30个提高Web程序执行效率的好经验分享
2023-07-16 00:14:22
MySQL 去除重复数据实例详解
2024-01-24 13:21:53
列出SQL Server中具有默认值的所有字段的语句
2024-01-16 20:17:27
![](https://img.aspxhome.com/file/2023/1/91151_0s.jpg)
Python去除图片水印实现方法详解
2022-09-19 22:15:37
![](https://img.aspxhome.com/file/2023/2/101162_0s.png)