Python if else循环连接对象 [英] Python if else loop concatenate objects

查看:80
本文介绍了Python if else循环连接对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Python if else循环,但是我得到了

I have a simple Python if else loop but I get an

错误:prev_word + = value_in无法连接str和int对象

error: prev_word += value_in cannot concatenate str and int objects

prev_word = 0
print_variable = 0

for line in sys.stdin:
        line = line.strip()       #strip out carriage return
        key_value = line.split('\t')   #split line, into key and value, returns a list   

        #note: for simple debugging use print statements, ie:  
        curr_word = key_value[0]         #key is first item in list, indexed by 0
        value_in = key_value[1]         #value is 2nd item

    if (value_in == "ABC"):
        print_variable = 1
    else:
        value_in = int(value_in)
        prev_word += value_in
    if (print_variable == 1):
        print( '%s\t%s' % (curr_word, prev_word) )
        print_variable = 0
    prev_word = curr_word

推荐答案

您即将在循环内部重新分配prev_word:

You are reassigning prev_word inside your loop at the very end:

prev_word = curr_word

重新分配后,初始化为intprev_word变为str,这将导致添加失败.

After this reassign, prev_word which is initialized to an int becomes a str and this causes your addition to fail.

动态类型的力量带来了巨大的责任.好的变量名是关键:)

With the power of dynamic types comes great responsibility. Good variable names are key :)

这篇关于Python if else循环连接对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆