请问有人可以帮我从我的元组列表中删除多余的括号吗?latest_Value = {"17:00:00": 100.00}Dict1 = {"current value": 100, "stock_purchased": "false", "Historic value": [('16:00:00', 55.50), ("15:00:00", 45.50), ("14:00:00", 75.50),("13:00:00", 65.50), ("12:00:00", 55.50)]}# converting the latest_value into a tupleList_it = [(k, v) for k, v in latest_Value.items()]# insert the tuple into the tuple listDict1['Historic value'].insert(0, List_it)data2 = Dict1["Historic value"]print(data2)#output [[('17:00:00', 100.0)], ('16:00:00', 55.5), ('15:00:00', 45.5), ('14:00:00', 75.5), ('13:00:00', 65.5), ('12:00:00', 55.5)]当列表被修改时,它会添加一个嵌套列表而不仅仅是元组。你如何避免这种情况?
1 回答
长风秋雁
TA贡献1757条经验 获得超7个赞
# converting the latest_value into a tuple List_it = [(k, v) for k, v in latest_Value.items()]
那实际上是错误的。这会将整个 dict 转换为元组,而不仅仅是最后一个键值对,因此Dict1['Historic value'].insert(0, List_it)
将整个元组列表添加到Dict1['Historic value']
.
latest_Value
包含单个键值对的事实不会改变将List_it
是元组列表的事实。
如果您更改为,Dict1['Historic value'].insert(0, List_it[0])
那么您将获得所需的输出。
添加回答
举报
0/150
提交
取消