python - Python 字典乘法键 * 值
问题描述
嘿,每个人都试图在 python 字典中乘以键 * 值。
我有以下代码:
dic = {'coca-cola':3, 'fanta':2}
def inventory(data):
lis = []
lis = [key * val for key, val in data.items()]
return lis
inventory(dic)
但是我的输出是
['coca-colacoca-colacoca-cola', 'fantafanta']
我想得到
['coca-cola', 'coca-cola', 'coca-cola', 'fanta', 'fanta']
请帮忙
解决方案
使用以下代码。
dic = {'coca-cola':3, 'fanta':2}
def inventory(data):
lis = []
for key, val in data.items():
for item in range(0,val):
lis.append(key)
return lis
推荐阅读
- ios - RxSwift 不会将数据从一个 ViewController 推回另一个
- azure - 在 Azure 存储上启用静态网站未显示在选项列表中
- android - buildSrc 中自定义 gradle 插件中的类不会打包到 apk 中
- java - 是这个错误org/apache/commons/logging/LogFactory java.lang.NoClassDefFoundError的Logger类方法的模拟解决方案吗?
- java - Google Cloud SQL api export csv:自定义分隔符,处理“N”值并设置 utf8mb64
- list - raku 从头到尾做转子的更好方法是什么?
- magento - Magento 2 + WHM + SSL + Varnish 配置问题
- vue.js - vue2-datepicker 不能禁用未来的日期
- arrays - 合并元组和 numpy 数组
- codeigniter - 如何一次自动加载 codeigniter4 库并在控制器、模型、视图中的每个位置访问它,就像在 CI3 中一样