zip()是 Python 的一個內建函數,用於將多個可迭代物件中的元素配對成元素組,本篇我們會來討論zip() 的主要用法。
合併兩個lists,將元素配對成tuples
names = ['DigNo', 'Ape', 'Nomad']
ages = [25, 30, 35]
paired = list(zip(names, ages))
print(paired)
解壓縮
paired = [['DigNo', 25], ['Ape', 30], ['Nomad', 35]]
names, ages = zip(*paired)
print(names)
print(ages)
創建字典
paired = [['DigNo', 25], ['Ape', 30], ['Nomad', 35]]
names, ages = zip(*paired) print(names)
print(ages)
迭代多個可迭代(iterable)物件
//List
names = ['DigNo', 'Ape', 'Nomad']
ages = [25, 30, 35]
cities = ['New York', 'Los Angeles', 'Chicago']
for name, age, city in zip(names, ages, cities):
print(f"{name} is {age} years old and lives in {city}.")
//Tuple
names = ('DigNo', 'Ape', 'Nomad')
ages = (25, 30, 35)
cities = ('New York', 'Los Angeles', 'Chicago')
for name, age, city in zip(names, ages, cities):
print(f"{name} is {age} years old and lives in {city}.")
//Set (集合是無序的,結果順序不一定可預測。)
names = {'DigNo', 'Ape', 'Nomad'}
ages = {25, 30, 35}
cities = {'New York', 'Los Angeles', 'Chicago'}
for name, age, city in zip(names, ages, cities):
print(f"{name} is {age} years old and lives in {city}.")
//String (不等長)
str1 = "dig"
str2 = "no"
str3 = "ape"
for char1, char2, char3 in zip(str1, str2, str3):
print(char1, char2, char3)
//Range (不等長)
range1 = range(4)
range2 = range(10, 15)
for a, b in zip(range1, range2):
print(a, b)
配對元素計算
a = [1, 2, 3]
b = [4, 5, 6]
sums = [x + y for x, y in zip(a, b)]
print(sums)
比較列表的元素
a = [1, 2, 3]
b = [1, 2, 4]
comparison = [x == y for x, y in zip(a, b)]
print(comparison)
過濾列表的元素
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
filtered = [(x, y) for x, y in zip(a, b) if x + y > 10]
print(filtered)
多個列表串聯
first_names = ['DigNo', 'Nomad']
last_names = ['Ape', 'Ape']
full_names = [f"{first} {last}" for first, last in zip(first_names, last_names)]
print(full_names)
條件合併
a = [1, 2, 3]
b = [4, 5, 6]
combined = [x if x % 2 == 0 else y for x, y in zip(a, b)]
print(combined)
謝謝您花時間將此篇文章讀完,若覺得對您有幫助可以幫忙按個讚、分享來或是珍藏喔!也歡迎Follow我的Threads,持續追蹤生產力工具、商業分析、商業英文,提升自己的職場力喔!