Python - 将列表转换为索引和值字典
当需要将列表转换为索引值字典时,使用“枚举”和简单迭代。
示例
以下是相同的演示-
my_list = [32, 0, 11, 99, 223, 51, 67, 28, 12, 94, 89]
print("Thelistis:")
print(my_list)
my_list.sort(reverse=True)
print("Thesortedlistis ")
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("Theresultis:")
print(my_result)输出结果Thelistis:
[32, 0, 11, 99, 223, 51, 67, 28, 12, 94, 89]
Thesortedlistis
[223, 99, 94, 89, 67, 51, 32, 28, 12, 11, 0]
Theresultis:
{'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迭代列表,并将索引和值附加到空列表。
这是显示在控制台上的输出。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下