首页 > 解决方案 > 如何在字典中存储 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]

标签: pythonlistdictionarymachine-learning

解决方案


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因为Noneappend()不会返回任何内容,它会就地修改列表。

如果您想将olabel的值复制到label然后执行此操作。

olabel.append(output)
label=olabel[:]

推荐阅读