簡體   English   中英

如何在沒有空格的數字串中添加每個數字

[英]How to add each digit in a string of numbers with no spaces

我目前正在嘗試在字符串輸入中獲取一系列數字,然后將這些數字轉換為要打印的總數。 從概念上講,這應該很容易,但我無法弄清楚。 我搜索了 Stack,但找不到適合我當前問題的解決方案。

這是我目前的進展:

def main():
numbers= input("Enter a sequence of numbers with no spaces:")
numbers= list(numbers)
total= ""
for i in numbers:
    total= total + i

print(total)

主要的()

我的邏輯是將數字序列分成一個列表,然后在循環中添加數字,然后生成總數。 不幸的是,這只返回原始字符串,所以我決定放:

對於我的數字:

i= eval(i)
total= total + i

對於我的數字:

i= int(i)
total= total + i

這將返回一個錯誤,指出 i 需要是一個字符串,但這只會導致另一個連接。

有誰知道如何生產我正在尋找的東西? 即“1234”= 10。

字符串本身是可迭代的,因此您可以對其進行迭代並將每個字符轉換為 int,然后使用 sum 將它們相加。

>>> numbers= input("Enter a sequence of numbers with no spaces:")
Enter a sequence of numbers with no spaces:1234567
>>> sum([int(i) for i in numbers])
28

或丟失外部[]以使其成為生成器表達式。 無論哪種方式它都可以工作,但是對於像這樣的小輸入,可以說生成器的開銷可能會超過其在內存使用方面的好處。

無需將字符串轉換為列表,因為它已經是可迭代的。 相反,只需執行以下操作:

numbers = input(‘Enter numbers: ‘)
total = 0

for char in numbers:
    total += int(char)

print(total)

這會遍歷字符串中的每個字符,將其轉換為整數,並將其添加到總數中。

只是在這里添加一個答案。 如果您接受的字符串是逗號分隔的,那么如果它是 python 2.7,那么這里是一個單行

 sequence = map(int, input().split(','))

否則為python3,

sequence = list(map(int, input().split(',')))

我希望它能為已經給出的答案添加一些東西。

暫無
暫無

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

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