0
点赞
收藏
分享

微信扫一扫

【Python】字典生成式

在前面

在这里插入图片描述
在这里插入图片描述

示例代码

# 昵 称:追光者♂
# 时 间: 2022/4/24/0024

items = ['Fruits', 'Books', 'Others']
prices = [99, 88, 77]

# 字典生成式

d = {item: price for item, price in zip(items, prices)}
print(d)

上述代码,将第一个列表当做‘键’。将第二个列表当做‘值’,根据“公式”,生成了一个“字典”。

在这里插入图片描述
写成 item.upper() 之后,可以将输出都变成大写。。。

items = ['Fruits', 'Books', 'Others']
prices = [99, 88, 77]

# 字典生成式

d = {item.upper(): price for item, price in zip(items, prices)}
print(d)

在这里插入图片描述
当数目不匹配时:

items = ['Fruits', 'Books', 'Others']
prices = [99, 88, 77, 100, 200]

# 字典生成式

d = {item.upper(): price for item, price in zip(items, prices)}
print(d)

上面有5个价格,那么输出是:

也就是说,以数目短的那个为基准进行匹配生成。
在这里插入图片描述

本章知识总结(见上面博客)

在这里插入图片描述

举报

相关推荐

0 条评论