python - 如何在字典中存储 2 个输出,一个作为键,另一个作为值
问题描述
python - 如何将2个输出一个作为键,另一个作为值存储在字典中,键和值是否在python中分别在输出中具有相应的索引
我做了什么:
olabel = []
ldate = []
label = olabel.append(output)
date = ldate.append(ld)
outputList = {label[i]:date[i] for i in range(10)}
我的 K 最近邻的 2 个输出将是输出和 ld。例如,我的 K 最近邻的前 2 个输出是:
output = 'Light1on'
ld = '2019-10-28 09:59:00'
输出应该是 outputList ,其中标签和日期将更新为各自的列表,这些列表将被制作成字典,它们的对应索引从它们的列表进入字典:
label=['Light1on']
date =['2019-10-28 09:59:00']
outputList = [Light1on:2019-10-28 09:59:00]
更新一次:
label=['Light1on','Light2on']
date =['2019-10-28 09:59:00','2019-10-28 10:59:00']
outputList = [Light1on:2019-10-28 09:59:00, Light2on:2019-10-28 10:59:00]
解决方案
zip()
可以用来实现你想要的。
label=["something","anything","nothing"]
date=['31st feb','32nd dec','1st jan']
outputList={i:j for i,j in zip(label,date)}
print(outputList)
输出:
{'something': '31st feb', 'anything': '32nd dec', 'nothing': '1st jan'}
代码中的错误
label = olabel.append(output)
date = ldate.append(ld)
无论您附加多少元素,label
因为None
它append()
不会返回任何内容,它会就地修改列表。
如果您想将olabel
的值复制到label
然后执行此操作。
olabel.append(output)
label=olabel[:]
推荐阅读
- javascript - 访问 Wiki API JSON 响应中的嵌套数据
- ruby-on-rails - 跨请求保持与第三方服务的连接
- python - 以编程方式检测图中的最佳拟合
- python - 在 DirectX 中实现 Python pyquaternion.rotation_matrix 函数
- python - 在 Python 中保存从 fbprophet 生成的图
- python-3.x - 将文件名信息解析为连接的 csv 文件中的多列
- python - 在嵌套循环中向 Python Dict 添加键/值时出错
- python - 如何从 C 运行 Python 脚本?
- jquery - jQuery Checkboxs 作为单选按钮,能够取消选中所有
- javascript - 无法在 Javascript 小书签中正确定位 iFrame