python学习zip函数

Python version: 3.7.4

zip主要用于同时获取多了list的值

1.zip与for循环组合,获取多个列表的元素

country = ["English", "Chinese", "Japanese"]
code = [44, 86, 81]

    for c, co in zip(country, code):
        print(c, co)

2.多个list组合

	country = ["English", "Chinese", "Japanese"]
	code = [44, 86, 81]
	time = ["20", "8", "9"]

	for c, co ,t in zip(country, code, time):
		print(c, co, t)

結果:

English 44 20
Chinese 86 8
Japanese 81 9

3.list长度不同时

	country = ["English", "Chinese", "Japanese", "Koren"]
	code = [44, 86, 81]
	time = ["20", "8"]

	for c, co ,t in zip(country, code, time):
		print(c, co, t)

結果:

English 44 20
Chinese 86 8

	from itertools import zip_longest

	country = ["English", "Chinese", "Japanese", "Koren"]
	code = [44, 86, 81]
	time = ["20", "8"]

	for c, co ,t in zip_longest(country, code, time):
		print(c, co, t)

結果:

English 44 20
Chinese 86 8
Japanese 81 None
Koren None None

fillvalue属性给予默认值

	from itertools import zip_longest

	country = ["English", "Chinese", "Japanese", "Koren"]
	code = [44, 86, 81]
	time = ["20", "8"]

	for c, co ,t in zip_longest(country, code, time, fillvalue="@@"):
		print(c, co, t)

結果:

English 44 20
Chinese 86 8
Japanese 81 @@
Koren @@ @@

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值