Python - 将整数拆分为各个数字(未知位数)

0 投票
4 回答
4777 浏览
提问于 2025-04-18 05:22

我们正在从一个文件中读取包含整数的行。读取的行数是不确定的。我们需要把每个整数拆分成它的每一位数字,然后把这些数字加起来,最后创建另一个文件,记录每个整数及其数字之和。

教授说要使用事件控制的循环,但没有进一步说明。我们只能使用 while 循环,而不能使用 for 循环。

我现在还不知道怎么把代码放在这里,以便展示我到目前为止测试的内容,主要是为了重新熟悉如何拆分整数中的数字。

编辑补充:

myFile = open("cpFileIOhw_digitSum.txt", "r")

numbers = 1
numberOfLines = 3
digitList = []
while(numbers <= numberOfLines):
    firstNum = int(myFile.readline())
    while (firstNum != 0):
        lastDigit = firstNum % 10
        digitList.append(lastDigit)
        firstNum = firstNum / 10
        firstDigit = firstNum
    digitList.append(firstDigit)
    digitSum = sum(digitList)
    print digitList
    print digitSum
    numbers += 1


myFile.close()

这是我目前的进展,但现在我遇到的问题是,我需要把每个整数的数字存储在不同的列表中。而且读取的整数数量是不确定的。用于计数和结束循环的数字只是示例。

我代码的最新更新:现在我主要想知道的是,如何让 while 循环知道文本文件中没有更多的行了。

myFile = open("cpFileIOhw_digitSum.txt", "r")
myNewFile = open("cpFileIOhw_output.txt", "w")

total = 0
fullInteger =
while(fullInteger != 0):
    fullInteger = int(myFile.readline())
    firstNum = fullInteger
    while (firstNum != 0):
        lastDigit = firstNum % 10
        total = total + lastDigit
        firstNum = firstNum / 10
        firstDigit = firstNum
    total = total + firstDigit
    myNewFile.write(str(fullInteger) + "-" + str(total))
    print " " + str(fullInteger) + "-" + str(total)
    total = 0


myFile.close()
myNewFile.close()

4 个回答

0

试试下面这个...

total = lambda s: str(sum(int(d) for d in s))

with open('u3.txt','r') as infile, open('u4.txt','w') as outfile:
    line = '.' # anything other than '' will do
    while line != '':
        line = infile.readline()
        number = line.strip('\n').strip()
        if line != '':
            outfile.write(number + ' ' + total(number) + '\n') 
                            # or use ',' instead of ' 'to produce a CSV text file
0

试试这个方法来把数字拆分成单个数字:

num = 123456
s = str(num)
summary = 0

counter = 0
while (counter < len(s)):
    summary += int(s[counter])
    counter += 1
print s + ', ' + str(summary)

结果:

C:\Users\Joe\Desktop>split.py
123456, 21

C:\Users\Joe\Desktop>
1

把整数转换成字符串其实没必要。因为你是从文本文件里读取整数,开始的时候你得到的就是字符串。

你需要一个外层的 while 循环来处理从文件中读取每一行。因为你不能使用 for 循环,所以我建议使用 my_file.readline(),当它返回一个空字符串时,就说明你已经读完文件了。

在这个循环里面,你还需要一个循环来处理拆分数字。不过——你的老师要求必须用两个循环吗?我记得你问题的编辑前提到过,但现在没有了。如果不需要的话,我建议直接用列表推导式。

1

好吧,这里有两种方法可以解决这个问题:

  • 把整数转换成字符串,然后逐个字符处理,再把每个字符转换回整数(最好用一个 for 循环来完成)。

  • 反复用这个整数除以10,得到商和余数;一直重复这个过程,直到商变成0为止(最好用一个 while 循环来完成)。

    你需要用到的数学运算符有:

    mod = 123 %  10     # 3
    div = 123 // 10     # 12
    

撰写回答