具有不同数字长度的CSV数据的Python布尔错误

2024-09-25 00:30:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用这个python脚本时,我遇到了布尔运算符处理不同数字长度的问题

with open ('data/idata.csv') as pdata: #Import Status CSV
readstatus = csv.reader(pdata, delimiter=',')
for row in readstatus:
    PN = row[0]
    Desc = row[1]
    Min = row[2]
    Stock = row[3]
    Assem = row[4]

    if (Assem == 'No'):
        print(PN+Min+Stock)
        if (Stock<Min):
            p.insert("",0,text=PN,values=(Desc, Stock))
        else:
            print('')
    else:
        print('')
pdata.close()

问题是:50>;25对;25>;假50例;150>;110对

但是。。。100>;25个错误…和12个>;2错误

注意:print语句仅用于调试

提前谢谢


Tags: csvgt脚本if错误stockminelse
2条回答
>>> '100'>'25'
False
>>> int('100')>int('25')
True

csv模块将字符串作为单元格值返回。和字符串在lexicographical order中相互比较,即11112和21are sorted exactly likea,aa,abandba`将按字母顺序排序

在本例中,如果值始终是整数,则希望将其转换为int;如果值是分数,则希望将其转换为floatDecimal

因此,您的固定代码

with open ('data/idata.csv') as pdata:
    readstatus = csv.reader(pdata, delimiter=',')
    for row in readstatus:
        PN = row[0]
        Desc = row[1]
        Min = int(row[2])
        Stock = int(row[3])
        Assem = row[4]

        if Assem == 'No':
            print(PN, Min, Stock)
            if Stock < Min:
                p.insert("", 0, text=PN, values=(Desc, Stock))
            else:
                print('')
        else:
            print('')

(还要注意,您不需要关闭pdata,因为这就是with语句的作用!)

相关问题 更多 >