【问题标题】:Python error in shell ValueError: invalid literal for int() with base 10:shell ValueError 中的 Python 错误:int() 的无效文字,基数为 10:
【发布时间】:2015-01-12 20:51:42
【问题描述】:

我正在编写一个程序。如果短匹配与长匹配混合。该程序是查看哪些匹配项将适合短框。 这是我的代码:

import math
def q2():

    fin = open('input.txt','rt')
    fout = open('output.txt', 'wt')
    a= int(fin.readline().strip())
    b = [int(b) for b in str(a)]
    count = -1
    nMatches = b[0]
    width = b[1]
    heigth = b[2]
    length = width**2 + heigth**2
    length = length**(.5)
    while count <= nMatches:
        match = int(fin.readline().strip())
        count = count+ 1
        if match <= length:
            print('YES')
        else:
            print('NO')

这是输出:

YES
YES
YES
NO
NO
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    q2()
  File "D:/code/Q2/q2.py", line 15, in q2
    match = int(fin.readline().strip())
ValueError: invalid literal for int() with base 10: ''

感谢您的帮助 fin的内容是: 534 3 4 5 6 7

【问题讨论】:

  • fin的内容是什么?
  • 你能打印match看看你得到了什么价值吗?
  • 也许我错了,但异常不仅表明他正在尝试将空字符串 '' 转换为 int 吗? 10 秒找到 4 个站点来解决这个问题。

标签: python regex shell int


【解决方案1】:

您似乎想将空字符串转换为 int。但这是不可能的。 看看你的异常: ... base 10: ''

所以你读了一行,你去掉它,然后只剩下一个空字符串。这会引发 ValueError

这里是一个 stackoverflow 答案(谷歌上的 1 oder 2 结果): ValueError: invalid literal for int() with base 10: ''

【讨论】:

    【解决方案2】:

    问题在于您的循环计数。为什么不使用while count &lt; nMatches 而不是for i in range(nMatches)?因为您的循环计数已关闭,所以您正在读取文件末尾,当您尝试转换空字符串时会出错。

    【讨论】:

      【解决方案3】:

      我在这里做了很多假设,因为我不知道fin 文件中的内容。这就是我认为你正在尝试做的事情: nMatches = 534 是框中的匹配数。 width = 3height = 4 不知何故导致框的 length 为 5

      我假设fin文件中前3个之后的所有数字都是每个匹配的长度。

          from math import sqrt
          def q2():
      
          fin = open('text.txt','r')
          fout = open('output.txt', 'w')
          a = fin.readline().strip().split()
          b = [int(x) for x in a]
          nMatches = b[0]
          width = b[1]
          height = b[2]
          length = sqrt(width**2 + height**2)
      
          for match in b[3:]:
      
              if match <= length:
                  print ('YES')
              else:
                  print ('NO')
      
          q2()
      

      这会将文件中的每个数字与框的长度进行比较。

      【讨论】:

        猜你喜欢
        • 2019-08-10
        • 1970-01-01
        • 1970-01-01
        • 2017-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多