Python:如果/ else语句,检查变量是否更大或更小

时间:2016-11-17 13:44:22

标签: python json

大家好!我正在使用Python 2.7xlrd.xlsx文件转换为.json文件!我想用这个脚本完成的是从输入中得出结论。这也将确保减少人为错误。但是,我的代码存在问题。用户必须在单元格中输入特定值,该单元格表示每个购买的书籍中的页面。我想要检查:是否有比100更多或更少的页面。我正在使用的代码

import sys
import xlrd

dir = '/path/to/JSON/to/write'
dirworksheet = '/path/to/excel/file'

file = sys.argv[1]
fileJSON = sys.argv[1]+'.json'

work_path = os.path.join(dirworksheet,file)
full_path = os.path.join(dir,fileJSON)
worksheet = xlrd.open_workbook(work_path)
sheet_generalinfo = worksheet.sheet_by_index(0)

data_generalinfo = []

for colnumber in range(1, sheet_generalinfo.ncols):
    key1 = OrderedDict()
    row_value = sheet_generalinfo.col_values(colnumber)
    key1['publish_id'] = 1
    key1['book_name'] = row_value[1]
    key1['pages_per_100'] = float(row_value[2])
    if row_value[2]>= 1:
        key1['greater_or_smaller']='greater'
    else:
        key1['greater_or_smaller']='smaller'

    key1['samples'] = data_samples

    data_generalinfo.append(key1)

json = json.dumps(data_generalinfo)

with open(full_path, 'w') as datafile: 
    datafile.write(json)

print(full_path)

代码工作正常!但是,当我查看JSON文件时,它总是说真的!我已在excel文件和0.3中输入1.4,但始终返回greater。我在这个陈述中做错了什么?

1 个答案:

答案 0 :(得分:3)

潜在的row_value [2]是导入时的字符串。如果是这样,那么它将永远是真的,因为它将字符串与数字进行比较:

>>> '0.1'>1
9: True

尝试将所有内容转换为浮点数:

key1['pages_per_100'] = float(row_value[2])

现在你已经让事情浮起来了,它会起作用,但你需要改变你的if语句:

for colnumber in range(1, sheet_generalinfo.ncols):
    key1 = OrderedDict()
    row_value = sheet_generalinfo.col_values(colnumber)
    key1['publish_id'] = 1
    key1['book_name'] = row_value[1]
    key1['pages_per_100'] = float(row_value[2])
    if row_value[2]>= 1:
        key1['greater_or_smaller']='greater'
    else:
        key1['greater_or_smaller']='smaller'

您将浮点值放入key1,但是if语句仍然会查看row_value,它仍然是一个字符串。改变这一行:

if row_value[2]>= 1:

改为:

if key1['pages_per_100']>= 1: