[python] 内置函数: zip()

zip()

作用

将复数个可循环类型(iterables)中的元素组装为一组tuple; 组装规则是根据各自所在的位置决定; 当最短的可循环类型内已经没有元素的时候, 组装终止

传入参数以及返回类型

  • 参数是可循环的数据类型, 例如数组, 元组, 字符串等
  • 返回类型是搭载复数元组的某种可循环类型

举例

# Combining two lists:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")

# Combining three lists:
colors = ["red", "green", "blue"]
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3]

for color, fruit, number in zip(colors, fruits, numbers):
    print(f"The {color} {fruit} is number {number}.")

# Using zip() with different lengths:
long_list = [1, 2, 3, 4, 5]
short_list = ["a", "b", "c"]

for item in zip(long_list, short_list):
    print(item)

输出结果

Alice is 25 years old.
Bob is 30 years old.
Charlie is 35 years old.
The red apple is number 1.
The green banana is number 2.
The blue cherry is number 3.
(1, 'a')
(2, 'b')
(3, 'c')

** Process exited - Return Code: 0 **
Press Enter to exit terminal

返回类型自定义

在zip()前转换类型即可

# 这段代码会返回一个数组
long_list = [1, 2, 3, 4, 5]
short_list = ["a", "b", "c"]

print(list(zip(long_list, short_list))) # output: [[1, 'a'], [2, 'b'], [3, 'c']]
posted @ 2024-02-18 16:05  Akira300000  阅读(4)  评论(0编辑  收藏  举报