【问题标题】:Python List - how to evaluate and replace blanks/nulls/spaces in the json string values to some default value? [duplicate]Python List - 如何评估json字符串值中的空白/空值/空格并将其替换为某个默认值? [复制]
【发布时间】:2020-12-25 08:06:24
【问题描述】:

假设,下面是输入列表,其中 exp_date 和 qty 字段为空白/空格/空。

input_lst = [
{
 "id": "123456",
 "product": "XYZ",
 "exp_date": "",
 "amount": "30.5",
 "qty": "1"
},
{
 "id": "789012",
 "product": "ABC",
 "exp_date": "04/15/2020",
 "amount": "22.57",
 "qty": "3"
},
{
 "id": "56789",
 "product": "AAA",
 "exp_date": "03/29/2020",
 "amount": "2",
 "qty": " "
}
]

我们可以像下面这样写 if/then/else - 什么是正确/适当的语法?

output_lst = []

for dct in input_lst:
    tmp_dct = dct.copy()
    try:
    #replace/default any blank/null/space values and convert to datetime
        tmp_dct['exp_date'] = datetime.strptime(if dct['exp_date'] == "" then '01/01/1900' else dct['exp_date'], '%m/%d/%Y')
    except:
        pass
    #replace/default any blank/null/space values and convert to int
    try:
        tmp_dct['qty'] = int(if dct['qty'] == '' then '1' else dct['qty'])
    except:
    output_lst.append(tmp_dct)
print(output_lst)

谢谢!

【问题讨论】:

    标签: python-3.x list replace null


    【解决方案1】:

    你必须改变你的三元运算符的顺序:

    output_lst = []
    
    for dct in input_lst:
        tmp_dct = dct.copy()
        try:
            #replace/default any blank/null/space values and convert to datetime
            tmp_dct['exp_date'] = datetime.strptime('01/01/1900' if dct['exp_date'] == "" else dct['exp_date'], '%m/%d/%Y')
        except:
            pass
    
        try:
            #replace/default any blank/null/space values and convert to int
            tmp_dct['qty'] = 1 if dct['qty'].strip() == '' else int(dct['qty'])
        except:
            pass
    
        output_lst.append(tmp_dct)
    print(output_lst)
    

    您还必须注意字段qty,在您的示例中可以包含空格。在这种情况下,最好使用strip() 来删除开头和/或结尾的所有空格。

    【讨论】:

      猜你喜欢
      • 2011-04-28
      • 2013-11-04
      • 2021-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      相关资源
      最近更新 更多