在 Python 中将元组元素提升为另一个元组的幂
当需要将一个元组的元素提升为另一个元组的幂次时,可以使用“zip”方法和生成器表达式。
zip 方法获取可迭代对象,将其聚合为一个元组,并将其作为结果返回。
生成器是一种创建迭代器的简单方法。它自动实现一个具有“__iter__()”和“__next__()”方法的类,并跟踪内部状态以及在不存在可返回的值时引发“StopIteration”异常。
以下是同样的演示:
示例
my_tuple_1 = ( 7, 8, 3, 4, 3, 2)
my_tuple_2 = (9, 6, 8, 2, 1, 0)
print ("The first tuple is : " )
print(my_tuple_1)
print ("The second tuple is : " )
print(my_tuple_2)
my_result = tuple(elem_1 ** elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))
print("The tuple raised to power of another tuple is : ")
print(my_result)输出
The first tuple is : (7, 8, 3, 4, 3, 2) The second tuple is : (9, 6, 8, 2, 1, 0) The tuple raised to power of another tuple is : (40353607, 262144, 6561, 16, 3, 1) > The first tuple is : (7, 8, 3, 4, 3, 2) The second tuple is : (9, 6, 8, 2, 1, 0) The tuple raised to power of another tuple is : (40353607, 262144, 6561, 16, 3, 1)
说明
- 定义了两个元组,并显示在控制台上。
- 迭代这些列表,并使用“zip”方法将它们压缩。
- 使用“**”运算符,从两个元组中获取第一个元素作为第二个元素的幂。
- 然后将其转换为元组。
- 此操作被分配给一个变量。
- 此变量是要显示在控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP