简体   繁体   English

有人可以向我解释为什么python 3.4在没有我明确要求的情况下将字符串解析为int

[英]Can someone explain to me why python 3.4 is parsing a string to an int without me explicitly asking for it

I am so confused it's beyond belief, it's probably a noobie mistake, but I am thoroughly befuddled by this behavior. 我很困惑,这令人难以置信,这可能是一个愚蠢的错误,但是我对此行为完全迷住了。 Here's the small algorithm (as I think it should be): 这是小算法(我认为应该如此):

a, b, n = input().split()
x = 0

def prod(num):
    x=1
    for y in range(len(num)):
        if int(num[y])>0:
           x*=int(num[y])
    x+=int(num)
    return x

while x < int(n):
    a, b = b, prod(b)+prod(a)
    print(b, end=' ')
    x+=1

and here's how I apparently have to do it to make it work: 这显然是我必须要做的才能使它起作用:

a, b, n = input().split()
x = 0

def prod(num):
    x=1
    for y in range(len(str(num))):
        if int(str(num)[y])>0:
           x*=int(str(num)[y])
    x+=int(num)
    return x

while x < int(n):
    a, b = b, prod(b)+prod(a)
    print(b, end=' ')
    x+=1

so if it isn't clear, my problem is in the prod function. 因此,如果不清楚,我的问题出在prod函数中。 it seems to convert the string to an int for no apparent reason. 似乎没有明显的原因将字符串转换为int。

the input I'm giving it is 1 100 3 and is supposed to be of that format. 我给它的输入是1 100 3 ,应该是这种格式。

Python is not implicitly turning your string into an integer, no. Python不会将您的字符串隐式转换为整数,不。 Instead, you are giving your function an integer. 而是给函数一个整数。

You are returning an integer from prod() and in the next operation, you pass that integer to the prod() function. 您要从prod()返回一个整数,然后在下一个操作中,将该整数传递给prod()函数。

The steps are: 这些步骤是:

  1. a, b, n = '1', '100', '3'
  2. call prod('100') + prod('1') , produces 101 + 2 is 3 , an integer. 调用prod('100') + prod('1') ,产生101 + 23 ,是整数。
  3. a, b = '100', 3 , so now b is an integer, go to the next iteration. a, b = '100', 3 ,所以现在b是整数,转到下一个迭代。
  4. call prod(3) + prod('100') ; 调用prod(3) + prod('100') ; you are passing in an integer to your function. 您正在向函数传递整数。

Perhaps you need to convert the sum to return a string from prod() instead? 也许您需要转换总和以从prod()返回字符串? Change your return statement to: 将您的退货单更改为:

return str(x)

or perhaps the sum of the prod() results should be a string: 或者prod()结果的总和应该是一个字符串:

a, b = b, str(prod(b) + prod(a))

You can simplify your function to just iterating over num directly, and use the fact that single characters have an order too: 您可以将函数简化为直接迭代num ,并使用单个字符也具有顺序的事实:

def prod(num):
    x = 1
    for digit in num:
        if digit > '0':
           x *= int(digit)
    x += int(num)
    return x  # or `str(x) if a string is expected

Your while loop should just be a for loop with range() : 您的while循环应该只是带有range()for循环:

for iteration in range(int(n)):
    a, b = b, str(prod(b) + prod(a))
    print(b, end=' ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM