簡體   English   中英

Python - 將整數拆分為單個數字(未確定的數字位數)

[英]Python - Split integer into individual digits (undetermined amount of digits)

我們正在從包含整數的文件中讀取行。 讀取的行數不確定。 我們必須將每個整數分成整數的數字,然后將這些數字加在一起並創建另一個文件,該文件以整數和每個整數的數字之和進行寫入。

教授說使用事件控制的循環,但沒有指明。 我們只被允許使用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循環知道txt文件中沒有剩余的行。

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()

那么,有兩種方法可以解決這個問題:

  • 將整數轉換為字符串並遍歷每個字符,將每個字符轉換回int(最好用for循環完成)

  • 反復得到將整數除以10的被除數和模數; 重復直到被除數為0(最好用while循環完成)。

    這些是您需要的數學運算符:

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

不需要將整數轉換為字符串。 由於您正在從文本文件中讀取整數,因此您將從字符串開始。

你需要一個外部while循環來處理從文件中讀取的行。 由於你被禁止使用for循環,我會使用my_file.readline() ,你知道你在返回一個空字符串時已經完成了讀取文件。

嵌套在該循環中,你需要一個處理拉開數字。 雖然 - 你的教授需要兩個循環嗎? 我認為你的問題在編輯之前說過,但現在卻沒有。 如果不需要,我會使用列表理解。

嘗試將其拆分為數字:

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>

試試以下......

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM