尝试打印列表内容时,为什么要打印索引?

时间:2019-06-24 17:30:25

标签: python string list for-loop indexing

我正在尝试将用户提供的数字中的每个数字平方。我得到正确的输出,但是最后我得到一个额外的索引,我不确定为什么。我已经在代码中添加了注释,以解释我在每个步骤中想要做的事情。最后如何摆脱该索引?

def square_digits(num):

    print(num)

    string_num =(str(num)) #convert the num to a string   

    for word in string_num: #iterate through every digit 

        word = int(word) #convert each digit to an int so we can square it
        square_num = word * word
        str_sq_num = list(str(square_num)) #create a list of those nums

        for count in str_sq_num:  #iterate through list to make it one number  
            print(count, end = "")  


    print(str_sq_num)
    return str_sq_num

因此,给出了一个示例编号3212。我应该输出9414,而不是9414['4']。另一个示例是数字6791,输出应为3649811,但我的输出为3649811['1']

3 个答案:

答案 0 :(得分:1)

问题是循环在python中工作的方式。变量str_square_numfor word in string_num上一次迭代的结果。

例如,假设您的数字为12,则在第一次迭代中str_square_num将为[1]1的平方。但是,当此值设置为[4]或2平方时,它将在第二次迭代中覆盖。因此,数组将始终只包含最后一位的平方。

如果您的目标是获取所有指标的数组,请尝试以下操作:

def square_digits(num):
    print(num)
    string_num =(str(num)) #convert the num to a string
    str_sq_num = []

    for word in string_num: #iterate through every digit 

        word = int(word) #convert each digit to an int so we can square it
        square_num = word * word
        str_sq_num.extend(str(square_num)) #create a list of those nums

    for count in str_sq_num:  #iterate through list to make it one number  
        print(count, end = "")  


    print(str_sq_num)
    return str_sq_num

答案 1 :(得分:0)

我不确定您要在此实现什么,但是查看您的示例,我想这应该可行:

def square_digits(num):
    print(num)

    string_num = (str(num))
    str_sq_num = []

    for word in string_num:
        word = int(word)
        square_num = word * word
        str_sq_num.append(square_num)
    for count in str_sq_num:
        print(count, end = "")

    return str_sq_num

答案 2 :(得分:0)

无法测试,但这应该可以做到:

def square_digits(string_num):

return "".join([str(int(num)**2) for num in string_num])