Python中函数式编程函数:zip函数

自由坦荡的智能 2025-02-17 02:12:06

zip(*可迭代对象)

Python 中的 zip() 函数用于将多个可迭代对象(如列表或元组)组合成元组,其中每个元组都包含来自输入可迭代对象相应位置的元素。星号 (*) 运算符可用于解压缩可迭代对象的可迭代对象,从而有效地转置数据。在需要对不同列表中的元素进行配对或重新组织数据结构的情况下,此操作特别有用。

# Original lists names = ['Ebi', 'Cyrus', 'Charlie'] scores = [85, 92, 78] # Using zip to combine lists into tuples combined = list(zip(names, scores)) print("Combined:", combined) # Output: [('Ebi', 85), ('Cyrus', 92), ('Charlie', 78)] # Using zip with unpacking to transpose the combined data unzipped = list(zip(*combined)) print("Unzipped:", unzipped) # Output: [('Ebi', 'Cyrus', 'Charlie'), (85, 92, 78)] # Accessing individual components unzipped_names, unzipped_scores = unzipped print("Names:", unzipped_names) # Output: Names: ('Ebi', 'Cyrus', 'Charlie') print("Scores:", unzipped_scores) # Output: Scores: (85, 92, 78)
0 阅读:15
自由坦荡的智能

自由坦荡的智能

感谢大家的关注