【问题标题】:Python thinks 100 is less than 50?Python认为100小于50?
【发布时间】:2017-01-24 16:18:18
【问题描述】:

这是我的代码:

stock_file  = open('Task_3_1.txt', "rt") #open file
stock_lines = stock_file.readlines() #convert items to list
total_buys = []
total_cost = []
done = 0
for o in range(0,(len(stock_lines)-1)): 
    edit = list(stock_lines[o])
    for m in range(1,2): #convert file to array
        edit.remove(edit[len(edit)-1])
    stock_lines[o] = ''.join(edit)
to_do = input("1. Find items that need to be restocked\n")
if to_do == "1":    
    x = 1
    while x < len(stock_lines):
        if stock_lines[x] < stock_lines[x+1]:        
            print(stock_lines[x-1], "needs restocking (" + stock_lines[x] +  " stock, restock level is", stock_lines[x+1] +")")
        x+=4 #increases x to check the next item

我的问题是,运行时,它的目的是打印出需要补货的东西(哪些库存水平低于补货水平)。这是我正在使用的股票文件:

Egg
100
50
75
Crocodile clip
30
12
30
Chocolate
206
300
390

第一行是商品名称,然后是库存水平,然后是补货水平,然后是目标库存水平(补货时商品的库存量)。

当我运行这个时:

1. Find items that need to be restocked
1
Egg needs restocking (100 stock, restock level is 50)
Chocolate needs restocking (206 stock, restock level is 300)

如您所见,它告诉我 100 小于 50。任何帮助都会很棒。

我已经尝试将 100 更改为 101 以查看双零是否影响它。

【问题讨论】:

  • 您是否有机会将"100" &lt; "50" 字符串与字符串进行比较?
  • 嗯...你的标题“Python认为100大于50?”可能不是你的意思...
  • 附带说明,我想您应该将if to_do == "1" 编辑为if to_do == 1 在我将其更改为整数比较之前它对我不起作用。

标签: python arrays windows file numbers


【解决方案1】:
>>> '100' < '50'
True
>>> 100 < 50
False

【讨论】:

【解决方案2】:

您正在比较 字符串

"100" < "50"

因为 1 在 5 之前。

修复如下:

if int(stock_lines[x]) < int(stock_lines[x+1]):     

【讨论】:

    【解决方案3】:

    更改为int(stock_lines[x]) &lt; int(stock_lines[x+1])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-08
      相关资源
      最近更新 更多