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

时间:2018-12-20 15:56:30

标签: python python-3.x

我的名单是['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

5 个答案:

答案 0 :(得分:2)

  

将字符串的'1''2'转换为1,2是整数打印   由于包含“ to”字符串,因此无法将其转换为错误消息   整数

source = ['1', '2', 'to', '3']
result = []

for item in source:
    try:
        result.append(int(item))
    except ValueError as ex:
        print('Not integer: {}'.format(item))

print(result)

答案 1 :(得分:2)

几件事:

  • 执行此操作的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

答案 2 :(得分:1)

尝试将每个项目转换为结果列表。如果转换失败,则输出错误消息。

l = ['1','2','to','3']

result = []
for item in l:
    try:
        result.append(int(item))
    except ValueError:
        print(item)

答案 3 :(得分:1)

您可以使用render (){ return ( <Doughnut data={this.state.chartData} options={{ padding:"0px", responsive:false, maintainAspectRatio:false, defaultFontSize:"14px", width:"400", height:"400", legend:{ display:false, }, plugins:{ datalabels: { color:'#000000', anchor: "start", align:"end", formatter: function(value, context) { return context.chart.data.labels[context.dataIndex]; } } } }} /> ) } / try块将有效的整数文字与其他所有内容分开:

except

对于您而言,您可以只在candidates = ['1','2','to','3'] for candidate in candidates: try: # attempt the conversion value = int(candidate) except ValueError: # conversion failed! print(candidate, 'is not an integer') else: # conversion succeeded print(candidate, 'is the integer', value) 子句中收集值:

else

答案 4 :(得分:0)

l = ['1', '2', 'word', '4']

您可以这样做:

n = [int(i) if i.isdigit() else print('\nNot able to convert: '+i) for i in l]

输出:

Not able to convert: word
l = [1, 2, None, 4]