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 遍歷列表,並將索引和值追加到空列表中。
這是顯示在控制檯上的輸出。
廣告