在 Python 中将元组转换为邻接对词典
如果需要将元组转换为邻接对词典,可以使用“dict”方法、词典推导式和切片。
词典以 (键、值) 对的形式存储值。词典推导式是遍历词典并对其执行操作的简写形式。
切片将给定较低索引值到给定较高索引值的迭代器中存在的值提供出来,但将较高索引值处的元素排除在外。
以下是对其进行演示 −
示例
my_tuple_1 = (7, 8, 3, 4, 3, 2)
print ("The first tuple is : " )
print(my_tuple_1)
my_result = dict(my_tuple_1[idx : idx + 2] for idx in range(0, len(my_tuple_1), 2))
print("The dictionary after converting to tuple is: ")
print(my_result)输出
The first tuple is :
(7, 8, 3, 4, 3, 2)
The dictionary after converting to tuple is:
{7: 8, 3: 2}说明
- 定义了一个元组并显示在控制台上。
- 使用“dict”方法对元组中的每个元素进行迭代,将元组转换为词典。
- 将此结果分配给一个变量。
- 将其作为输出显示在控制台上。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP