Python – 用字典列表中的第 K 個索引值替換值
當需要用字典列表的第 K 個索引值替換值時,會用到 ‘isinstance’ 方法和一個簡單的迭代。
示例
下面是透過演示實現的
my_list = [{'python': [5, 7, 9, 1], 'is': 8, 'good': 10},
{'python': 1, 'for': 10, 'fun': 9},
{'cool': 3, 'python': [7, 3, 9, 1]}]
print("The list is :")
print(my_list)
K = 2
print("The value of K is")
print(K)
my_key = "python"
for index in my_list:
if isinstance(index[my_key], list):
index[my_key] = index[my_key][K]
print("The result is :")
print(my_list)輸出
The list is :
[{'python': [5, 7, 9, 1], 'is': 8, 'good': 10}, {'python': 1, 'fun': 9, 'for': 10}, {'python': [7, 3, 9, 1], 'cool': 3}]
The value of K is
2
The result is :
[{'python': 9, 'is': 8, 'good': 10}, {'python': 1, 'fun': 9, 'for': 10}, {'python': 9, 'cool': 3}]說明
定義了一個字典列表並顯示在控制檯上。
如果 K 存在,則顯示在控制檯上。
定義關鍵元素。
遍歷列表,使用 ‘isinstance’ 方法檢查特定元素是否與列表型別相同。
如果是,則將 K 值放置在特定元素之中。
這是控制檯上顯示的輸出。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP