【问题标题】:Troubles converting from string to int python从字符串转换为int python的麻烦
【发布时间】:2016-04-07 11:23:27
【问题描述】:

我正在研究这个编码难题,并且必须将字符串中的一些数字转换为整数才能使用它们。一个例子是

('2 -5 7 8 10 -205')

我试图做的是将数字添加到一个空字符串中,并在有空格时将它们转换为 int。这是代码。

n 是数字字符串的长度 num 是我添加数字的空字符串。原来是 num=""

  while i<n:

    if temps[i]!=' ':
        num=num+temps[i]


    elif temps[i]==' ':
        print type(num)

        x=int(num)

问题是当它运行时我得到一个错误,x=int(num) 说

ValueError: invalid literal for int() with base 10: ''

当我打印 num 时,我只得到字符串格式的数字,所以我不明白出了什么问题。非常感谢您的帮助,如果您有任何问题或需要澄清,请提出。

谢谢

【问题讨论】:

    标签: python string int type-conversion


    【解决方案1】:

    使用str.split() 在空格处拆分字符串,然后将int 应用于每个元素:

    s = '2 -5 7 8 10 -205'
    nums = [int(num) for num in s.split()]
    

    【讨论】:

    • 是的,正是我写的:)
    【解决方案2】:

    如果你的字符串是这样的:

    s = '2 -5 7 8 10 -205'
    

    您可以使用列表推导式创建整数列表。首先,您将在空白处拆分字符串,并单独解析每个条目:

    >>> [int(x) for x in s.split(' ')]
    [2, -5, 7, 8, 10, -205] ## list of ints
    

    【讨论】:

      【解决方案3】:

      您可以通过列表推导来做到这一点:

      data = ('2 -5 7 8 10 -205')
      l = [int(i) for i in data.split()]
      print(l)
      [2, -5, 7, 8, 10, -205]
      

      或者您也可以使用map 函数:

      list(map(int, data.split()))
      [2, -5, 7, 8, 10, -205]
      

      基准测试

      In [725]: %timeit list(map(int, data.split()))
      100000 loops, best of 3: 2.1 µs per loop
      
      In [726]: %timeit [int(i) for i in data.split()]
      100000 loops, best of 3: 2.54 µs per loop
      

      所以使用地图可以更快地运行

      注意list 已添加到地图中,因为我使用的是 python 3.x。如果您使用的是 python 2.x,则不需要。

      【讨论】:

        【解决方案4】:

        您应该尝试将任务拆分为 2 个子任务:

        1. 使用split将字符串中的数字拆分为数字列表
        2. 使用映射map将列表中的每个字符串转换为常规整数

        作为一般建议 - 您还应该阅读文档,以便了解通过将一个函数的输出链接为下一个函数的输入可以节省多少辛勤工作。

        【讨论】:

          【解决方案5】:

          内置方法也可以完成这项工作:

          >>> s = '2 -5 7 8 10 -205'
          >>> map(int, s.split())
          [2, -5, 7, 8, 10, -205]
          

          如果 Python 3+:

          >>> s = '2 -5 7 8 10 -205'
          >>> list(map(int, s.split()))
          [2, -5, 7, 8, 10, -205]
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-05-15
            • 1970-01-01
            • 2020-09-16
            • 1970-01-01
            相关资源
            最近更新 更多