【问题标题】:How to convert a list of strings to integers in python? [duplicate]如何在python中将字符串列表转换为整数? [复制]
【发布时间】:2020-10-09 22:40:10
【问题描述】:
list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']

我有一个包含 10 个项目的列表。如何将其转换为整数列表?由于列表中的“测试”,我遇到了错误。

【问题讨论】:

标签: python python-3.x list function jupyter-notebook


【解决方案1】:

不要直接调用列表list。 (它隐藏了内置的 list 函数,以后可能会给您带来奇怪的错误!)

假设您只想忽略非数字值,您可以通过在最后使用过滤器在理解中执行此操作:

>>> [int(x) for x in [
...     '5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test'
... ] if x.lstrip('-').isdigit()]
[5, 12, 4, 3, 5, 14, 16, -2, 4]

【讨论】:

    【解决方案2】:

    假设你想忘记错误的值,那该怎么办

    list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
    list2 = []
    for _ in list:
        try:
            list2.append(int(_))
        except:
            pass
    
    print(list2)
    

    执行:

    >>> list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
    >>> list2 = []
    >>> for _ in list:
    ...     try:
    ...         list2.append(int(_))
    ...     except:
    ...         pass
    ... 
    >>> print(list2)
    [5, 12, 4, 3, 5, 14, 16, -2, 4]
    >>> 
    

    【讨论】:

    • 裸 except: 很少是个好主意。
    • @jonrsharpe 是的,但正如我在答案开头所说的supposing you want to forget wrong values,当然如果目标不同,实施也必须如此^^
    • 对,但这并不意味着使用except:。绝对最低限度except Exception:,但相应错误的名称在您所写的内容中是正确的。
    • @jonrsharpe 那个时候我不确定你的意思是什么,你的意思是表示我在执行append() 时有一个例外(但int(_) 可以)?
    • @TrentonMcKinney 在“正常”情况下是的,因为这隐藏了错误,但我的答案以supposing you want to forget wrong values 开头,所以即使是这种情况也必须默默隐藏。
    【解决方案3】:

    使用int() 转换字符串并使用.isnumeric() 确保字符串表示数字。

    str_arr = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
    int_arr = []
    
    for s in str_arr:
        if s.strip('-').isnumeric():
            int_arr.append(int(s))
    
    print(int_arr)
    

    【讨论】:

      【解决方案4】:
      list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
      
      new_list = []
      for i in list:
          try:
              new_list.append(int(i))
          except ValueError:
              print("String found")
      

      【讨论】:

        【解决方案5】:

        保留列表中的所有值:

        t = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
        
        t = [int(v) if v.lstrip('-').isnumeric() else v for v in t]
        
        print(t)
        
        # output
        [5, 12, 4, 3, 5, 14, 16, -2, 4, 'test']
        

        删除非数字值:

        t = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
        
        t = [int(v) for v in t if v.lstrip('-').isnumeric()]
        
        print(t)
        
        # output
        [5, 12, 4, 3, 5, 14, 16, -2, 4]
        

        嵌套列表:

        t = [['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test'] for _ in range(3)]
        
        t = [[int(v) if v.lstrip('-').isnumeric() else v for v in x] for x in t]
        
        print(t)
        
        # output
        [[5, 12, 4, 3, 5, 14, 16, -2, 4, 'test'],
         [5, 12, 4, 3, 5, 14, 16, -2, 4, 'test'],
         [5, 12, 4, 3, 5, 14, 16, -2, 4, 'test']]
        

        【讨论】:

          【解决方案6】:

          您收到错误,因为字母无法转换为整数。但是整数可能会转换为字符串。

          你可以通过使用'try'和'except'来解决你的问题

          我会告诉你怎么做的

          for i in range(len(list)):
              try:
                  list[i] = int(list[i])
              except:
                  print(i,'cannot be converted to string')
          

          try 和 except 语句的工作方式与 if 和 else 语句一样。如果代码中没有错误,则“try”语句将起作用。只要有错误,except语句就会生效。

          你可以把它想象成:

          if (no_error):           #try statement
              do_these_things      
          elif (any_error):        #except statement
              do_these_instead
          

          【讨论】:

            【解决方案7】:

            请尝试以下代码:

            list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
            list1=[]
            for i in list:
                if(i.isnumeric()==True):
                    list1.append(i)
                else:
                    continue
            print(list1)
            

            【讨论】:

              【解决方案8】:

              使用以下代码:

              list = ['5', '12', '4', '3', '5', '14', '16', '-2', '4', 'test']
              
              print([int(i) for i in list if i.lstrip('+-').isdigit()])
              

              这将给出以下输出:

              [5, 12, 4, 3, 5, 14, 16, -2, 4]
              

              【讨论】:

              • 我猜这个输出是 not OP 所期望的,'-2'.isdigit() 是 False。
              • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
              • 嘿,我更新我的代码
              猜你喜欢
              • 2011-09-16
              • 2013-09-08
              • 2011-11-23
              • 2019-03-01
              • 2010-11-22
              • 1970-01-01
              • 2023-03-06
              • 2013-02-28
              • 2019-10-21
              相关资源
              最近更新 更多