我目前正在阅读本书: Introduction to Computation and Programming Using Python。
我目前正在处理的问题是:
设s是一个包含由逗号分隔的十进制数字序列的字符串,例如
s = '1.23,2.4,3.123'
。编写一个程序,打印s
中的数字总和。
我已经想出了整数的方法:
s = raw_input('Enter any positive integers: ')
total = 0
for c in s:
c = int(c)
total += c
print total
我尝试了几种方法,包括try和except方法,但我可以弄清楚如何解决
Valuerror:invalid literal for int() with base 10: '.'
我感谢任何帮助。谢谢。
更新:我要感谢每个人的帮助。很高兴知道有人愿意帮助小乔。
答案 0 :(得分:2)
sum(map(float,raw_input("Enter any positive integers: ").split(',')))
这是一种快速而肮脏的单线作为快速黑客攻击。这里展开了一点:
input_string = raw_input("Enter any positive integers: ")
#input_string is now whatever the user inputs
list_of_floats_as_strings = input_string.split(",")
#this splits the input up across commas and puts a list in
#list_of_floats_as_strings. They're still strings here, not floats yet,
#but we'll fix that in a moment
running_total = 0 #gotta start somewhere
for value in list_of_floats_as_strings:
number = float(value) #turn it into a float
running_total+=number #and add it to your running total
#after your for loop finishes, running_total will be the sum you're looking for
关于快速脏单线的确切做法:
sum( #tells Python to add up everything inside the brackets
map( #tells Python to run the designated function on everything in the
#iterable (e.g. list or etc) that follows
float, #is the float() function we used in the unrolled version
raw_input("Enter any positive integers: ") #is your input
.split(',') #splits your input into a list for use in map
)
)
请不要像我刚才那样编写代码。将那些脏的单行保持为脏的单行,并在之后解释它们。我认为这种格式对于一次性解释可能更好,但是对于文档而言,它确实更糟糕。
答案 1 :(得分:1)
使用split
和float
,例如
s = raw_input('Enter any floats: ')
print s
items = s.split(",")
print "items:",items
floats = map(float, items)
print "floats:",floats
total = sum(floats)
print "total:",total
输出为
Enter any floats: 12.3,45.6,78.9
12.3,45.6,78.9
items: ['12.3', '45.6', '78.9']
floats: [12.3, 45.6, 78.9]
total: 136.8
答案 2 :(得分:1)
这是使用for循环的解决方案。
# Save the string (e.g. '12.5,67.4,78.5')
number_string = raw_input("Enter any positive floats: ")
# Initialize a variable to hold the sum of the numbers
tot = 0
# Iterate over all numbers in the string. The string is splitted
# at each comma, thus resulting in a list like `['12.5', '67.4', '78.5']`
for num in number_string.split(','):
# But every element in the list is a string, so you need to
# convert them to floats, and add each of them to the total sum
tot += float(num)
# Print the total sum
print tot
正如其他人所指出的那样,通过编写更少的代码,您可以更轻松地完成此任务,但这可能更容易理解。当您理解这一点时,您可能会理解其他解决方案的工作原理。