YAML+PyYAML笔记 3 | YAML集合、结构、标量、标记使用
1 集合
YAML 支持三种集合类型:列表,映射和集。
1.1 列表
- 列表是一种序列结构,它使用连字符
“-”
表示; - 如下三个元素的列表,元素之间用
“-”
:
fruit:
- apple
- rubber
- pear
- 使用
Pyyaml
解析:
# 解析
with open("config_jihe.yaml") as f:
yaml_data2 = yaml.load(f, Loader=yaml.FullLoader)
print(yaml_data2)
# 输出
{'fruit': ['apple', 'rubber', 'pear']}
1.2 映射
- 即一种键值对结构,它使用冒号
“:”
表示; - 如下:
fruit:
- apple
- rubber
- pear
vegetable:
green: cucumber
red: tomato
yellow: corn
- 使用
Pyyaml
解析:
{'fruit': ['apple', 'rubber', 'pear'], 'vegetable': {'green': 'cucumber', 'red': 'tomato', 'yellow': 'corn'}}
1.3 集
- 无序不重复的数据类型;
- 用大括号
“{}”
表示;
tree: {poplar, willow, pine}
{'tree': {'poplar': None, 'willow': None, 'pine': None}}
2 结构
- 可用于任何数据类型的复杂性结构;
- 包括集合和其他数据类型。
2.1 多行结构
- 表示复杂数据类型的方式;
- 如下:
vegetable:
green: cucumber
red: tomato
yellow: corn
tree:
one: poplar
two: willow
three: pine
{'vegetable': {'green': 'cucumber', 'red': 'tomato', 'yellow': 'corn'}, 'tree': {'one': 'poplar', 'two': 'willow', 'three': 'pine'}}
2.2 单行结构
- 在一行上表示复杂的结构:
- 如下:
data: {vegetable: {green: cucumber, red: tomato, yellow: corn}, tree: {one: poplar, two: willow, three: pine}}
{'data': {'vegetable': {'green': 'cucumber', 'red': 'tomato', 'yellow': 'corn'}, 'tree': {'one': 'poplar', 'two': 'willow', 'three': 'pine'}}}
3 字面量
- 字面量可以表示字符串、数字、布尔值、
null
值等;
# 字符串:在双引号中使用转义符号来表示特殊字符
str: "Hello,\\nWorld!"
# 数字:可以表示整数和浮点数
int: 88888
float: 3.141592653
# 布尔值:可以使用true和false表示
boolean: true
# null 值:使用 null 来表示空值
empty: null
- 使用
Pyyaml
解析:
{'str': 'Hello,\\nWorld!', 'int': 88888, 'float': 3.141592653, 'boolean': True, 'empty': None}
4 标量
- 分为单引号、双引号和无引号;
# 单引号:表示精确字符串,不会进行转义
single: 'Hello,\nworld!'
# 双引号:表示标准字符串,可以进行转义
double: "Hello,\\nworld!"
# 无引号:可以识别特殊字符,但空格会自动被转义成字符串
none: hello world
{'single': 'Hello,\\nworld!', 'double': 'Hello,\\nworld!', 'none': 'hello world'}
5 标记
# !!str:表示字符串类型。如:
key: !!str string
# !!int:表示整数类型。如:
key: !!int 123
# !!float:表示浮点数类型。如:
key: !!float 3.14
# !!bool:表示布尔类型。如:
key: !!bool true
# &name:为数据定义一个锚点,可以在后面使用锚点引用。如:
person: &p
name: xiaozhang
age: 88
student:
<<: *p
grade: 100
6 指示符
- 指示符包括用于描述
YAML
文档内容的特殊语义:
编号 | 字符 | 功能 |
---|---|---|
1 | _ | 表示块序列条目 |
2 | ? | 表示映射键 |
3 | : | 表示映射值 |
4 | , | 表示流集合条目 |
5 | [ | 开始流序列 |
6 | ] | 结束流序列 |
7 | { | 启动流映射 |
8 | } | 结束流映射 |
9 | # | 表示注释 |
10 | & | 表示节点的锚属性 |
11 | * | 表示别名节点 |
12 | ! | 表示节点的标签 |
13 | Ι | 表示一个字面块标量 |
14 | > | 表示折叠块标量 |
15 | ' | 单引号围绕引用的流标量 |
16 | " | 双引号包围双引号流标量 |
17 | % | 表示使用的指令 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧