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