Python – 将列表转换为索引和值字典
当需要将列表转换为索引值字典时,可以使用“enumerate”和简单的迭代。
示例
以下是该操作的演示 −
my_list = [32, 0, 11, 99, 223, 51, 67, 28, 12, 94, 89]
print("The list is :")
print(my_list)
my_list.sort(reverse=True)
print("The sorted list is ")
print(my_list)
index, value = "index", "values"
my_result = {index : [], value : []}
for id, vl in enumerate(my_list):
my_result[index].append(id)
my_result[value].append(vl)
print("The result is :")
print(my_result)输出
The list is :
[32, 0, 11, 99, 223, 51, 67, 28, 12, 94, 89]
The sorted list is
[223, 99, 94, 89, 67, 51, 32, 28, 12, 11, 0]
The result is :
{'index': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'values': [223, 99, 94, 89, 67, 51, 32, 28, 12, 11, 0]}说明
定义一个整数列表,并将其显示在控制台上。
该列表按逆序排列,并显示在控制台上。
对索引和值进行初始化以显示。
使用 enumerate 遍历列表,并将索引和值追加到空列表中。
这是显示在控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP