当前位置: 首页 > news >正文

字典或者列表常用方法介绍

列表变成字典的方法:

    #使用字典推导式d={k:v for k,v in enumerate(nums)}#{0: 2, 1: 11, 2: 7, 3: 15, 4: 26, 5: 12, 6: 6, 7: 9}#使用 enumerate()(索引作键)d=dict(enumerate(nums,start=1))#{1: 2, 2: 11, 3: 7, 4: 15, 5: 26, 6: 12, 7: 6, 8: 9}##使用字典推导式d={m:1 for m in nums}#{2: 1, 11: 1, 7: 1, 15: 1, 26: 1, 12: 1, 6: 1, 9: 1} 

enumerate()
enumerate() 用于在循环中同时获取索引和值。

# 基本语法:enumerate(iterable, start=0)
fruits = ['apple', 'banana', 'orange']# 不使用 enumerate
for i in range(len(fruits)):print(f"索引 {i}: {fruits[i]}")# 使用 enumerate(更优雅)
for index, fruit in enumerate(fruits):print(f"索引 {index}: {fruit}")

输出:
索引 0: apple
索引 1: banana
索引 2: orange

从1开始计数
for index, fruit in enumerate(fruits, start=1):

dict.get() 方法

get() 方法用于安全地获取字典中的值,避免 KeyError

# 基本语法:dict.get(key, default=None)
student = {'name': 'Alice', 'age': 20, 'city': 'Beijing'}# 传统方法(可能报错)
# score = student['score']  # KeyError: 'score'# 使用 get() 方法(安全)
score = student.get('score')
print(score)  # None# 指定默认值
score = student.get('score', 0)
print(score)  # 0# 存在的键正常返回
name = student.get('name', 'Unknown')
print(name)  # Alice

字典推导式
{key: value for 循环变量 in 可迭代对象}
即:
{key_expression: value_expression for item in iterable}
字典推导式的完整语法包含可选的条件过滤:
{key_expression: value_expression for item in iterable if condition}

# 创建数字平方的字典
squares = {x: x*x for x in range(1, 6)}
print(squares)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}# 等价的传统写法
squares = {}
for x in range(1, 6):squares[x] = x * x
# 列表转字典
fruits = ['apple', 'banana', 'orange']
fruit_dict = {i: fruit for i, fruit in enumerate(fruits)}
print(fruit_dict)  # {0: 'apple', 1: 'banana', 2: 'orange'}# 字符串处理
words = ['hello', 'world', 'python']
length_dict = {word: len(word) for word in words}
print(length_dict)  # {'hello': 5, 'world': 5, 'python': 6}

带条件过滤

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# 只保留偶数
even_squares = {x: x*x for x in numbers if x % 2 == 0}
print(even_squares)  # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}# 多重条件
filtered = {x: x**3 for x in numbers if x > 3 and x < 8}
print(filtered)  # {4: 64, 5: 125, 6: 216, 7: 343}
# 键和值都进行转换
original_dict = {'a': 1, 'b': 2, 'c': 3}
# 交换键值对
swapped = {v: k for k, v in original_dict.items()}
print(swapped)  # {1: 'a', 2: 'b', 3: 'c'}
# 处理元组列表
students = [('Alice', 85), ('Bob', 92), ('Charlie', 78)]
grade_dict = {name: score for name, score in students}
print(grade_dict)  # {'Alice': 85, 'Bob': 92, 'Charlie': 78}

总结
字典推导式的优点:
代码简洁、可读性好
执行效率通常比传统循环高
函数式编程风格
适用场景:
简单的数据转换和过滤
从其他数据结构创建字典
字典的批量更新和转换
items函数介绍
items() 是处理字典时最常用、最强大的方法之一!

dict.items() 返回一个视图对象,包含字典的所有键值对。

person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}# 获取items视图
items_view = person.items()
print(items_view)  # dict_items([('name', 'Alice'), ('age', 25), ('city', 'Beijing')])# 在循环中使用
for key, value in person.items():print(f"{key}: {value}")# 输出:
# name: Alice
# age: 25
# city: Beijing
person = {'name': 'Alice', 'age': 25}
items_view = person.items()
print(list(items_view))  # [('name', 'Alice'), ('age', 25)]# 修改原字典
person['city'] = 'Beijing'  # 添加新键值对
person['age'] = 26         # 修改值# 视图对象会自动更新
print(list(items_view))  # [('name', 'Alice'), ('age', 26), ('city', 'Beijing')]

转换为列表

person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}# 转换为元组列表
items_list = list(person.items())
print(items_list)  # [('name', 'Alice'), ('age', 25), ('city', 'Beijing')]# 转换为字典列表(每个键值对作为一个字典)
dict_list = [{k: v} for k, v in person.items()]
print(dict_list)  # [{'name': 'Alice'}, {'age': 25}, {'city': 'Beijing'}]

条件过滤

scores = {'math': 85, 'english': 92, 'science': 78, 'history': 65}# 找出高分科目(>=80)
high_scores = {subject: score for subject, score in scores.items() if score >= 80}
print(high_scores)  # {'math': 85, 'english': 92}# 找出需要改进的科目
need_improvement = [(subject, score) for subject, score in scores.items() if score < 70]
print(need_improvement)  # [('history', 65)]

与其他方法的对比
items() vs keys() vs values()

person = {'name': 'Alice', 'age': 25, 'city': 'Beijing'}print("items():", list(person.items()))   # 键值对
print("keys():", list(person.keys()))     # 只有键
print("values():", list(person.values())) # 只有值# 输出:
# items(): [('name', 'Alice'), ('age', 25), ('city', 'Beijing')]
# keys(): ['name', 'age', 'city']  
# values(): ['Alice', 25, 'Beijing']

字典合并与更新

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}# 合并字典(Python 3.9+ 有更简单的方法)
merged = {k: v for d in [dict1, dict2] for k, v in d.items()}
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}# 更新值(基于条件)
scores = {'math': 85, 'english': 92, 'science': 78}
adjusted = {subject: score+5 if score < 90 else score for subject, score in scores.items()}
print(adjusted)  # {'math': 90, 'english': 92, 'science': 83}
http://www.dtcms.com/a/609196.html

相关文章:

  • 计算机网络中的地址体系全解析(包含 A/B/C 类地址 + 私有地址 + CIDR)
  • SpringBoot教程(三十四)| SpringBoot集成本地缓存Caffeine
  • 专业摄影网站推荐专业做卖菜的网站
  • Hadess V1.2.5版本发布,新增推送规则、制品扫描等,有效保障制品质量与安全
  • 华清远见25072班单片机高级学习day1
  • Apache Flink运行环境搭建
  • Node.js(v16.13.2版本)安装及环境配置教程
  • Flutter 每日库: device_info_plus获取设备详细信息
  • 小马网站建设网站备案好
  • 做某网站的设计与实现网页设计代码案例
  • 生产级 Rust Web 应用架构:使用 Axum 实现模块化设计与健壮的错误处理
  • 大模型三阶段训练:预训练、SFT、RLHF解决的核心问题
  • 记/基准] RELIABLE AND DIVERSE EVALUATION OF LLM MEDICAL KNOWLEDGE MASTERY
  • TensorFlow深度学习实战(9)——卷积神经网络应用
  • LeetCode 分类刷题:203. 移除链表元素
  • 【Qt开发】Qt窗口(一) -> 菜单栏
  • Python的json模块和jsonpath模块
  • Crawl4ai 框架的学习与使用
  • hadoop节点扩容和缩容操作流程
  • RDF 与 RDFS:知识图谱推理的基石
  • 最新轻量版域名防红跳转源码 带后台 支持随机跳转有效放屏蔽
  • linux: udp服务器与客户端 CS 基于ipv4的地址结构体
  • 做食品网站需要什么条件手机靓号网站建设
  • 运筹说145期:从快递到自动驾驶:启发式算法的智慧幕后
  • 如何选择合适的养老服务机器人
  • 微博评论数据采集:基于Requests的智能爬虫实战
  • 数据挖掘概述
  • 51c自动驾驶~合集43
  • Go语言反编译:深入分析与技术探索 | 从原理到实践,全面解析Go反编译的实现和应用
  • ASP.NET Core 10