[英]Summing elements of string in Python
我是python的新手。 我開始讀由麻省理工學院教授出版的有關python的書。 我從這本書中得到了練習。 我試圖解決這個問題,但我做不到。
問題:讓s是一個字符串,其中包含一個用逗號分隔的十進制數字序列,例如s ='1.23,2.4,3.123'。 編寫一個程序,打印s中的數字之和。 我必須找出1.23、2.4和3.123的總和
到目前為止,我已經編寫了一些代碼來解決此問題,而我的代碼正在關注:
s = '1.23,2.4,3.123'
total = 0
for i in s:
print i
if i == ',':
拜托,有人幫我可以走得更遠嗎?
使用str.split()
更簡單,例如
s = '1.23,2.4,3.123'
total = 0
for i in s.split(','):
total += float(i)
遍歷字符串並逐步增加數字的內容要少得多,而且需要付出更多的努力,但它可能更符合初學者的工作精神,並且更多地是原始代碼的延續:
s = '1.23,2.4,3.123'
total = 0
number_holder_string = ''
for character in s:
if character == ',': # found the end of a number
number_holder_value = float(number_holder_string)
total = total + number_holder_value
number_holder_string = ''
else:
number_holder_string = number_holder_string + character
print total
這樣,number_holder_string變為:
''
'1'
'1.'
'1.2'
'1.23'
found a comma -> convert 1.23 from string to value and add it.
''
'2'
'2.'
etc.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.