Python函数中的数字字符串转换

问题描述:

我目前正在学习python,所以我提前为我的代码的混乱道歉。我的函数是为了接受一个字符串并将字符串数字加在一起。即一个123的字符串参数将变成1 + 2 + 3并返回6. 我的问题是当我迭代我的列表 - python一直指示变量已被引用之前,任何值已被分配。但是,当我打印出正在计算的值时,它们是正确的。更令人困惑的是,当我返回他们时 - 他们是不正确的。我似乎无法弄清楚我要出错的地方。谁能告诉我这个问题可能是什么?Python函数中的数字字符串转换

谢谢!

listy = [] 
global total 
#Convert number to a list then cycle through the list manually via elements  and add them all up 
def digit_sum(x): 
    number= [] 
    number.append(x) 
    print number 

    for i in range(len(number)): 
     result = str(number[i]) 
     print result 

     #Now it has been converted to a string so we should be able to 
     #read each number separately now and re-convert them to integers 
     for i in result: 
      listy.append(i) 
      print listy 
      #listy is printing [5,3,4] 

     for i in listy: 
      total += int(i) 
      return total 

print digit_sum(x) 
+0

有谁能告诉我为什么这是低票?我仍然对堆栈溢出感到陌生,所以这是否有这样的投票理由?缺乏清晰度吗? – azurekirby

+0

你有正确的概念,但可以通过使用其他内置功能来使其更清洁。 我注意到的一件事是你的'return'语句嵌套在最后一个for循环中。您需要取消缩进,以便每次循环迭代时都不会调用它。 – Flyer1

我相信我已经弄清楚我的代码出了什么问题。由于我对Python还是一个新手,我提出了一些非常新手的错误,比如没有意识到在本地函数之外声明变量会导致解决方案不符合我的预期。

由于我的退货放置不正确,以及我的函数外部实例化了我的listy []变量,而不是读取每个数字一次,它会读取三次。

这现在已经在下面的代码中得到纠正。

#Convert number to a list then cycle through the list manually via elements and add them all up 
def digit_sum(x): 
    total = 0 
    number= [] 
    number.append(x) 
    print number 

    for i in range(len(number)): 
     result = str(number[i]) 
     print result 

     #Now it has been converted to a string so we should be able to 
     #read each number separately now and re-convert them to integers 

     for i in result: 
      listy = [] 
      listy.append(i) 
      # print listy 
      #listy is printing [5,3,4] 

      for i in listy: 
       print i 
       total+= int(i) 
       print total 
       break 

    return total 

print digit_sum(111) 

我真的不知道发生了什么事情在你的代码存在,尤其是与搞砸缩进,但是你的问题很容易sovled:

sum(map(int, str(534))) 

它使一个字符串的数字,然后将每个数字转换为intmap,然后将其总和。

+0

我现在还在学习Python - 我对缩进道歉。我现在要修复它。 但534只是测试函数 - 它可以是任何数字字符串参数。 – azurekirby

+0

嗨马尔蒂森,感谢您的方法。你觉得我的代码混淆了什么? – azurekirby

如果您关注的是只有总结了一串号码,然后列出理解本身会做或@Maltysen建议你可以使用地图

sum([int(x) for x in "534"]) 

很简单: 可以使用地图或列表理解。他们几乎相当。其他人使用地图给出了答案,但我决定使用列表理解。

s = "1234567" 
sum([int(character) for character in s]) 

无视此答案,不应该在这里发布它。