【问题标题】:Converting items in list to int with specific condition (Python)将列表中的项目转换为具有特定条件的 int (Python)
【发布时间】:2021-07-21 14:21:07
【问题描述】:

我有一个由字符组成的字符串,所有字符都用逗号分隔,我想创建一个仅包含整数的列表。我写道:

str = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'.replace(' ','')
# Now the str without spaces: '-4,,5,170.5,4,s,k4,4k,1.3,,,8'

lst_str = [item for item in str.split(',')
# Now I have a list with the all items: ['-4', '5', '170.5', '4' ,'s', 'k4' ,'4k', '1.3', '8']

int_str = [num for num in lst_str if num.isdigit]
# The problem is with negative character and strings like '4k'
# and 'k4' which I don't want, and my code doesn't work with them.

#I want this: ['-4', '5', '4', '8'] which I can changed after any item to type int.

有人可以帮我怎么做吗?无需导入任何类。 我没有找到这个特定问题的答案(这是我的第一个问题)

【问题讨论】:

  • 在 EAFP 之后,您可以编写一个将 str 转换为 int 的函数,方法是调用 int 并处理像 Nones 这样的异常,然后过滤掉它们

标签: python list integer conditional-statements


【解决方案1】:

isdigit() 是一个函数,而不是属性。应该使用() 调用它。它也不适用于负数,您可以删除检查的减号

int_str = [num for num in lst_str if num.replace('-', '').isdigit()]
# output: ['-4', '5', '4', '8']

如果你需要避免'-4-'的情况,使用出现次数参数

num.replace('-', '', 1)

【讨论】:

  • 谢谢!这对我来说是最好的:)
【解决方案2】:

试试这个:

def check_int(s):
    try: 
        int(s)
        return True
    except ValueError:
        return False
    
int_str = [num for num in lst_str if check_int(num)]

【讨论】:

    【解决方案3】:

    我是用这个来做的:

    string = '-400,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'.replace(' ','')
    # Now the str without spaces: '-4,,5,170.5,4,s,k4,4k,1.3,,,8'
    
    let_str = [item for item in string.split(',')]
    # Now I have a list with the all items: ['-4', '5', '170.5', '4' ,'s', 'k4' ,'4k', '1.3', '8']
    neg_int = [num for num in let_str if "-" in num]
    
    int_str = [num for num in let_str if num.isdigit()]
    neg_int = [num for num in neg_int if num[1:].isdigit()]
    
    for num in neg_int: int_str.append(num)
    print(int_str)
    

    【讨论】:

      【解决方案4】:

      如果你将它与python: extract integers from mixed list结合起来,这非常接近问题Python - How to convert only numbers in a mixed list into float?

      您的“过滤器”根本没有过滤 - 名为 num 的非空字符串实例上的函数 num.isdigit 始终为真。

      您使用整数而不是浮点数:创建一个尝试将某些内容解析为整数的函数,如果不返回 None。 只保留那些不是 None 的。

      text  = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'    
      cleaned = [i.strip() for i in text.split(',') if i.strip()]
      
      def tryParseInt(s):
          """Return integer or None depending on input."""
          try:
              return int(s)
          except ValueError:
              return None
      
      # create the integers from strings that are integers, remove all others 
      numbers = [tryParseInt(i) for i in cleaned if tryParseInt(i) is not None]
      
      print(cleaned)
      print(numbers)
      

      输出:

      ['-4', '5', '170.5', '4', 's', 'k4', '4k', '1.3', '8']
      [-4, 5, 4, 8]
      

      【讨论】:

        【解决方案5】:

        正则表达式解决方案怎么样:

        import re
        
        str = '-4,, 5, 170.5,4,s, k4, 4k, 1.3,  ,, 8'
        int_str = [num for num in re.split(',\s*', str) if re.match(r'^-?\d+$', num)]
        

        【讨论】:

          【解决方案6】:

          你可以尝试用这个函数替换 num.isdigit :

          def isNumber(str):
              try:
                  int(str)
                  return True
              except:
                  return False
          

          例如:int_str = [num for num in lst_str if isNumber(num)]

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-24
            • 2021-11-21
            • 1970-01-01
            • 1970-01-01
            • 2022-12-17
            • 2017-04-29
            相关资源
            最近更新 更多