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 @@ @@

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章