我正在阅读Guttag博士撰写的《使用Python计算和编程入门》一书。我正在为第3章进行手指练习。它是第25页的3.2节。练习是:让s是一个字符串,其中包含一个用逗号分隔的十进制数字序列,例如s = '1.23,2.4,3.123'
。编写一个程序,打印s中数字的和。
上一个示例是:
total = 0
for c in '123456789':
total += int(c)
print total.
我已经尝试了很多,但是不断出现各种错误。这是我最近的尝试。
total = 0
s = '1.23,2.4,3.123'
print s
float(s)
for c in s:
total += c
print c
print total
print 'The total should be ', 1.23+2.4+3.123
我得到ValueError: invalid literal for float(): 1.23,2.4,3.123.
浮点值不能有逗号。您正在传递1.23,2.4,3.123
,因为它是浮点函数,无效。首先根据逗号分割字符串,
s = "1.23,2.4,3.123"
print s.split(",") # ['1.23', '2.4', '3.123']
然后将列表中的每个元素都转换为浮动元素,并将其相加以获得结果。要感受到Python的强大功能,可以通过以下方式解决此特定问题。
您可以找到total
,就像这样
s = "1.23,2.4,3.123"
total = sum(map(float, s.split(",")))
如果元素的数量太大,则可以使用生成器表达式,如下所示
total = sum(float(item) for item in s.split(","))
所有这些版本将产生与以下相同的结果
total, s = 0, "1.23,2.4,3.123"
for current_number in s.split(","):
total += float(current_number)
我的答案在这里:
s = '1.23,2.4,3.123'
sum = 0
is_int_part = True
n = 0
for c in s:
if c == '.':
is_int_part = False
elif c == ',':
if is_int_part == True:
total += sum
else:
total += sum/10.0**n
sum = 0
is_int_part = True
n = 0
else:
sum *= 10
sum += int(c)
if is_int_part == False:
n += 1
if is_int_part == True:
total += sum
else:
total += sum/10.0**n
print total
我设法用到3.2节为止的知识来回答问题
s = '1.0, 1.1, 1.2'
print 'List of decimal number'
print s
total = 0.0
for c in s:
if c == ',':
total += float(s[0:(s.index(','))])
d = int(s.index(','))+1
s = s[(d+1) : len(s)]
s = float(s)
total += s
print '1.0 + 1.1 + 1.2 = ', total
这是一个问题的答案,我认为拆分功能对像您和我这样的初学者不利。
考虑到您可能尚未接触到更复杂的功能,只需尝试一下。
total = 0
for c in "1.23","2.4",3.123":
total += float(c)
print total
我的回答:
s = '2.1,2.0'
countI = 0
countF = 0
totalS = 0
for num in s:
if num == ',' or (countF + 1 == len(s)):
totalS += float(s[countI:countF])
if countF < len(s):
countI = countF + 1
countF += 1
print(totalS) # 4.1
仅在数字为浮点数时才有效
这是我的答案。它与上面的user5716300相似,但是由于我也是初学者,因此为拆分字符串显式创建了一个单独的变量s1:
s = "1.23,2.4,3.123"
s1 = s.split(",") #this creates a list of strings
count = 0.0
for i in s1:
count = count + float(i)
print(count)
[如果我们只是坚持本章的内容,我想出了这一点:(尽管使用theFourthEye提到的sum方法也很漂亮):
s = '1.23,3.4,4.5'
result = s.split(',')
result = list(map(float, result))
n = 0
add = 0
for a in result:
add = add + result[n]
n = n + 1
print(add)
s = input('Enter a sequence of decimal numbers separated by commas: ')
x = ''
sum = 0.0
for c in s:
if c != ',':
x = x + c
else:
sum = sum + float(x)
x = ''
sum = sum + float(x)
print(sum)
此刻仅使用本书已涵盖的思想。基本上,它遍历原始字符串s中的每个字符,使用字符串加法将每个字符添加到下一个以构建新的字符串x,直到遇到逗号为止,此时它将x的内容更改为浮点数并将其添加到以零开头的sum变量。然后将x重置为空字符串,并重复直到覆盖s中的所有字符
我只想发布我的答案,因为我正在读这本书。
s = '1.23,2.4,3.123'
ans = 0.0
i = 0
j = 0
for c in s:
if c == ',':
ans += float(s[i:j])
i = j + 1
j += 1
ans += float(s[i:j])
print(str(ans))
我认为这是回答问题的最简单方法。它使用split命令,该命令目前未在书中介绍,但它是非常有用的命令。
s = input('Insert string of decimals, e,g, 1.4,5.55,12.651:')
sList = s.split(',') #create a list of these values
print(sList) #to check if list is correctly created
total = 0 #for creating the variable
for each in sList:
total = total + float(each)
print(total)
total =0
s = {1.23,2.4,3.123}
for c in s:
total = total+float(c)
print(total)
由于您是从Python开始的,所以可以尝试这种简单的方法:
使用split(c)
功能,其中c
是定界符。有了这个,您将有一个列表numbers
(在下面的代码中)。然后,您可以遍历该列表的每个元素,将每个数字强制转换为float
(因为numbers
的元素是字符串)并求和:
numbers = s.split(',')
sum = 0
for e in numbers:
sum += float(e)
print sum
输出:
6.753
摘自第25页的使用Python进行计算和编程简介。
“是一个包含以逗号分隔的十进制数字序列的字符串,例如s='1.23,2.4,3.123'。编写一个打印s中数字之和的程序。“
如果仅使用到目前为止所教的内容,那么此代码是一种方法:
tmp = ''
num = 0
print('Enter a string of decimal numbers separated by comma:')
s = input('Enter the string: ')
for ch in s:
if ch != ',':
tmp = tmp + ch
elif ch == ',':
num = num + float(tmp)
tmp = ''
# Also include last float number in sum and show result
print('The sum of all numbers is:', num + float(tmp))
total = 0
s = '1.23,2.4,3.123'
for c in s.split(','):
total = total + float(c)
print(total)
像魅力一样仅使用了我所学到的内容
s = raw_input('Enter a string that contains a sequence of decimal ' +
'numbers separated by commas, e.g. 1.23,2.4,3.123: ')
s = "," + s+ ","
total =0
for i in range(0,len(s)):
if s[i] == ",":
for j in range(1,(len(s)-i)):
if s[i+j] == ","
total = total + float(s[(i+1):(i+j)])
break
print total
这是我想出的:
s = raw_input('Enter a sequence of decimal numbers separated by commas: ')
aux = ''
total = 0
for c in s:
aux = aux + c
if c == ',':
total = total + float(aux[0:len(aux)-1])
aux = ''
total = total + float(aux) ##Uses last value stored in aux
print 'The sum of the numbers entered is ', total
我认为自从提出这个问题以来,他们已经修订了这本教科书(其他一些人已经回答了。)我有第二版的教科书,拆分示例不在第25页上。本课之前没有任何内容向您展示如何使用拆分。
我最终发现使用正则表达式的另一种方式。这是我的代码:
# Intro to Python
# Chapter 3.2
# Finger Exercises
# Write a program that totals a sequence of decimal numbers
import re
total = 0 # initialize the running total
for s in re.findall(r'\d+\.\d+','1.23, 2.2, 5.4, 11.32, 18.1,22.1,19.0'):
total = total + float(s)
print(total)
[在学习新事物时,我从不认为自己会变得很沉密,但是到目前为止,本书的(大部分)手指练习都很难。
这里是不使用split
的解决方案:
s='1.23,2.4,3.123,5.45343'
pos=[0]
total=0
for i in range(0,len(s)):
if s[i]==',':
pos.append(len(s[0:i]))
pos.append(len(s))
for j in range(len(pos)-1):
if j==0:
num=float(s[pos[j]:pos[j+1]])
total=total+num
else:
num=float(s[pos[j]+1:pos[j+1]])
total=total+num
print total
我的工作方式:
s = '1.23, 211.3'
total = 0
for x in s:
for i in x:
if i != ',' and i != ' ' and i != '.':
total = total + int(i)
print total