在Python中使用Zip()进行平行迭代
#编程 #教程 #python #functions

您是否曾经听过“并行迭代”一词,或者在Python中编码时尝试“在多个迭代中循环”?

本教程将显示一个python zip()函数,该函数可帮助我们在多个迭代中执行并行迭代

定义

zip()函数需要迭代并在它们上进行迭代,从而从迭代中产生每个项目的元素。

items = ["Computer", "Keyboard", "CPU", "Mouse"]
units = [3, 2, 4, 6]

mapping = zip(items, units)

print(tuple(mapping))

输出

(('Computer', 3), ('Keyboard', 2), ('CPU', 4), ('Mouse', 6))

换句话说,它返回元素的迭代器,其中每个传递的迭代器中的第一个项目均配对,然后在每个传递的迭代器中第二个项目将配对在一起,然后一直持续到最短的迭代器

考虑zip()的另一种方法是将行变成列和列变成行。这类似于转移矩阵。Source

句法

Python zip()函数的语法是:

zip(*iterables)zip(iterator1, iterator2, ...)

在python 3.10中,添加了 strict 参数

zip(*iterables, strict=False)

我们将在本教程中看到strict的使用。

zip() 参数:

iterables:它们可以是可以迭代的列表,元素,词典或对象。

例子

languages = ["Python", "JavaScript", "C", "C++"]
founded = [1991, 1995, 1972, 1985]

mapping = zip(languages, founded)

print(list(mapping))

print(type(list(mapping)))

输出

[('Python', 1991), ('JavaScript', 1995), ('C', 1972), ('C++', 1985)]
<class 'list'>

zip()函数的工作

zip()函数如何创建元组的迭代器?

我们实际上可以说拉链意味着将两个单独的事物汇总到一个。

就像它一样, python zip() 功能可以通过取两个输入说 A1 A2,然后汇总该项目 A1 A2的相同索引数

我们将通过下面的插图更好地理解

zip function working

  • 我们可以清楚地看到,在右侧 - 0th Index的元组分别包含A1A2的每个项目。

  • A1A2的第1个索引上的项目也是如此。

  • 一般而言,索引i的元组包含A1A2中的index i的项目。

更形式地:zip()返回一个元素的迭代器,其中第i-th元组包含每个参数iTerables中的i-th element。 /p>

不同长度的迭代

如果迭代的长度不同,会发生什么?

,如果迭代传递给zip()函数的长度不同,则什么都不会发生。

示例

languages = ["Python", "JavaScript", "C", "C++"]
founded = [1991, 1995, 1972]

mapping = zip(languages, founded)

print(list(mapping))

输出

[('Python', 1991), ('JavaScript', 1995), ('C', 1972)]

在这里,C++被排除在外,因为founded变量仅包含三个参数。

如果Python在迭代量不同时会引发错误怎么办?

让我们以示例来理解

languages = ["Python", "JavaScript", "C", "C++"]
founded = [1991, 1995, 1972]

mapping = zip(languages, founded, strict=True)

print(list(mapping))

输出

Traceback (most recent call last):
  ....
ValueError: zip() argument 2 is shorter than argument 1

您是否注意到代码中还有其他参数strict=True

python版本3.10

中添加了strict参数

如果迭代的长度不同,并且我们使用strict参数,则代码将抛出ValueError。它对于调试可能很有用。

将一个或没有的iStos()传递给Zip()

zip() 函数如果没有传递参数,将返回一个空的迭代器。

no_iterable = zip()
print(list(no_iterable))

输出

[]

如果我们仅通过一个觉得,那么 zip() 函数将返回一个元素的迭代器,每个迭代者只有一个元素。

languages = ["Python", "JavaScript", "C", "C++"]

mapping = zip(languages)

print(list(mapping))

输出

[('Python',), ('JavaScript',), ('C',), ('C++',)]

python zip()示例

示例:使用 enumerate() zip()
函数

characters = ["Iron Man", "Thor", "Spiderman"]
real_names = ["RDJ", "Chris Hemsworth", "Andrew Garfield"]

result = zip(characters, real_names)

for num, results in enumerate(result):
    print(num, results)

输出

0 ('Iron Man', 'RDJ')
1 ('Thor', 'Chris Hemsworth')
2 ('Spiderman', 'Andrew Garfield')

示例:使用range()函数

name = ["Sachin", "Rishu", "Yashwant", "Abhishek"]

values = zip(range(4), name)

print(tuple(values))

输出

((0, 'Sachin'), (1, 'Rishu'), (2, 'Yashwant'), (3, 'Abhishek'))

示例:具有多个迭代

characters = ["Iron Man", "Thor", "Spiderman"]
real_names = ["RDJ", "Chris Hemsworth", "Andrew Garfield"]
reel_names = ["Tony Stark", "Thor", "Peter Parker"]

result = zip(characters, real_names, reel_names)

print(list(result))

输出

[('Iron Man', 'RDJ', 'Tony Stark'), ('Thor', 'Chris Hemsworth', 'Thor'), ('Spiderman', 'Andrew Garfield', 'Peter Parker')]

示例:输入到不同的数据类型

键入列表

characters = ["Iron Man", "Thor", "Spiderman"]
real_names = ["RDJ", "Chris Hemsworth", "Andrew Garfield"]

result = zip(characters, real_names)

print(f"List: {list(result)} and type is {type(list(result))}")

输出

List: [('Iron Man', 'RDJ'), ('Thor', 'Chris Hemsworth'), ('Spiderman', 'Andrew Garfield')] and type is <class 'list'>

键入字典

characters = ["Iron Man", "Thor", "Spiderman"]
real_names = ["RDJ", "Chris Hemsworth", "Andrew Garfield"]

result = zip(characters, real_names)

print(f"Dictionary: {dict(result)} and type is {type(dict(result))}")

输出

Dictionary: {'Iron Man': 'RDJ', 'Thor': 'Chris Hemsworth', 'Spiderman': 'Andrew Garfield'} and type is <class 'dict'>

打字到集合

characters = ["Iron Man", "Thor", "Spiderman"]
real_names = ["RDJ", "Chris Hemsworth", "Andrew Garfield"]

result = zip(characters, real_names)

print(f"Set: {set(result)} and type is {type(set(result))}")

输出

Set: {('Iron Man', 'RDJ'), ('Spiderman', 'Andrew Garfield'), ('Thor', 'Chris Hemsworth')} and type is <class 'set'>

打字到元组

characters = ["Iron Man", "Thor", "Spiderman"]
real_names = ["RDJ", "Chris Hemsworth", "Andrew Garfield"]

result = zip(characters, real_names)

print(f"Tuple: {tuple(result)} and type is {type(tuple(result))}")

输出

Tuple: (('Iron Man', 'RDJ'), ('Thor', 'Chris Hemsworth'), ('Spiderman', 'Andrew Garfield')) and type is <class 'tuple'>

解压缩值

我们实际上可以解压缩 。让我们看看如何做。

这可以在* asterisk operator的帮助下完成。

让我们以示例来理解。

characters = ["Iron Man", "Thor", "Spiderman"]
real_names = ["RDJ", "Chris Hemsworth", "Andrew Garfield"]
reel_names = ["Tony Stark", "Thor", "Peter Parker"]

mapping = zip(characters, real_names, reel_names)

mapped = list(mapping)

print(f"Zipped result: {mapped}", end="")

print("\n")

# unzipping values
char, real, reel = zip(*mapped)

print("Unzipped result:")

print(f"The characters list is : {char}")

print(f"The real_names list is : {real}")

print(f"The reel_names list is : {reel}")

输出

Zipped result: [('Iron Man', 'RDJ', 'Tony Stark'), ('Thor', 'Chris Hemsworth', 'Thor'), ('Spiderman', 'Andrew Garfield', 'Peter Parker')]

Unzipped result:
The characters list is : ('Iron Man', 'Thor', 'Spiderman')
The real_names list is : ('RDJ', 'Chris Hemsworth', 'Andrew Garfield')
The reel_names list is : ('Tony Stark', 'Thor', 'Peter Parker')

请注意,我们如何使用*解开可变mapped的值并存储未拉链的值,我们声明了三个变量charrealreel

结论

在本教程中,您已经学会了使用Python的zip()功能执行并行迭代,希望您了解如何使用它。

您现在了解zip()函数在幕后如何生成元组迭代器。

尝试上面写入的代码段以更好地理解代码。


如果您喜欢这个

,您可能会感兴趣的其他文章

How to convert bytes into strings in Python

f-string: An improved and modern way of string formatting

How to access the list values within the dictionary in Python

How to use __str__ and __repr__ to change the string representation of the objects in Python

How do sort() and sorted() functions are different from each other

What is the difference between seek() and tell() in Python

How to use tempfile module to create temporary files and dirs in Python


现在就全部。

保持编码