【Python】字典生成式

【Python】字典生成式,第1张

在前面


示例代码
# 昵 称:追光者♂
# 时 间: 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个价格,那么输出是:

也就是说,以数目短的那个为基准进行匹配生成。

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/730134.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存