如何解决Python:无法将json格式dict值放入列表
我试图从json输入中提取一组日期值。当我完成F_Date
的提取时,它是正确的。
2020-05-20T00:00:00
2020-05-18T00:00:00
2020-05-15T00:00:00
2020-05-13T00:00:00
我设置了一个包含值的列表,所以我想使用List[0]
之类的列表索引来获取列表中的第一个值或列表中的其他值,以作进一步的用途。但是,它失败了。它给了我第一列人物。如果我尝试使用List[1]
,它会给我一列0
而不是2020-05-18T00:00:00
,这正是我想要的。任何想法我的代码有什么问题吗?我对现在F_Date
是什么类型感到困惑,它不是列表吗?
谢谢。
F_Date = []
for cell in json["Cells"]:
if cell["ColumnName"] == "T":
if cell["RowIndex"] + 1 > 9:
F_Date = cell["DisplayValue"]
print(F_Date[0])
output:
2
2
2
2
Json:
json = {
"SheetName": "price","SheetIndex": 4,"Cells": [
{
"ColumnName": "T","RowName": "10","Address": "T10","ColumnIndex": 19,"RowIndex": 9,"Value": "2020-05-20T00:00:00","DisplayValue": "2020-05-20T00:00:00","ValueType": "Date"
},{
"ColumnName": "U","Address": "U10","ColumnIndex": 20,"Value": 2.75,"DisplayValue": 2.75,"ValueType": "Numeric"
},{
"ColumnName": "V","Address": "V10","ColumnIndex": 21,"Value": 2.15,"DisplayValue": 2.15,{
"ColumnName": "T","RowName": "11","Address": "T11","RowIndex": 10,"Value": "2020-05-18T00:00:00","DisplayValue": "2020-05-18T00:00:00","Address": "U11","Address": "V11","RowName": "12","Address": "T12","RowIndex": 11,"Value": "2020-05-15T00:00:00","DisplayValue": "2020-05-15T00:00:00","Address": "U12","Address": "V12","RowName": "13","Address": "T13","RowIndex": 12,"Value": "2020-05-13T00:00:00","DisplayValue": "2020-05-13T00:00:00","ValueType": "Date"
}
]}
解决方法
您需要做的只是打印F_Date而不是F_Date [0],后者仅打印第一个字符,因为字符串可以解释为字符列表,并且您正在打印索引0。
print(F_Date)
如果您对F_Date是什么感到困惑,则F_Date是您的日期字符串,因为它是您所获得的字典中键的值。
F_Date = []
for cell in json["Cells"]:
if cell["ColumnName"] == "T":
if cell["RowIndex"] + 1 > 9:
F_Date = cell["DisplayValue"] # Here you set F_Date to the value
print(F_Date[0])
我认为您要做的是
F_Date = []
for cell in json["Cells"]:
if cell["ColumnName"] == "T":
if cell["RowIndex"] + 1 > 9:
F_Date.append(cell["DisplayValue"])
print(cell["DisplayValue"])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。