Skip to main content
 首页 » 编程设计

python之如何检查列表中的整数和字符串

2025年05月04日14davidwang456

我的列表是['1','2','to','3']

我需要写一个逻辑

  • 把'1' '2'这个字符串转成1, 2这个整数
  • 打印错误消息,因为包含“to”字符串且无法转换为整数

这是我现在拥有的代码:

def average_file(filename): 
 
    inputFile = open(filename, "r") 
    inList = [] 
    results = [] 
    n = [] 
 
    for line in inputFile: 
        inList.append(line.strip())  #inList.append(line) 
        n = [int(elem) for elem in inList if elem.isdigit()] #I only remove the string and leave integer in my list, but I need a check logic to print error msg 
        results = list(map(int, n)) 
    inputFile.close() 
 
    results = sum(results)/len(results) 
    return results 

请您参考如下方法:

一些事情:

  • 执行此操作的 Pythonic 方法是期望它是一个全数字值,并在不是时处理错误。
  • 您可以使用 with 来处理您的文件生命周期。
  • 您可以在读取期间计算元素的总和和计数,而无需保存额外的数组(因此知道平均值)。
  • strip 在解析为 int 时是多余的 int(variable):

你去吧:

def average_file(filename): 
 
    summary = 0 
    count = 0 
 
    with open(filename, "r") as inputFile: 
        for line in inputFile: 
            try: 
                summary += int(line) 
                count += 1 
            except ValueError as e: 
                print('Can not parse "{0}" to a number'.format(line)) 
 
                # If reached here one of the values in the file is not a number and None is returned immediately 
                return None 
 
    # If count is 0 return None, otherwise return the average 
    return (summary / count) if count else None 

在 OP 的一些澄清之后编辑了答案:
当其中一个值不是数字时,立即返回 None。