gpt4 book ai didi

python - 从 python 2.7 中的字符串中提取多个 float

转载 作者:太空宇宙 更新时间:2023-11-04 10:40:25 25 4
gpt4 key购买 nike

我目前正在阅读这本书: Introduction to Computation and Programming Using Python .

我目前正在研究的问题是:

Let s be a string that contains a sequence of decimal numbers separated by commas, e.g., s = '1.23,2.4,3.123'. Write a program that prints the sum of the numbers in 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: '.'

我很感激任何帮助。谢谢。

更新:我要感谢大家的帮助。很高兴知道有人愿意帮助小乔。

最佳答案

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

请永远不要像我刚才那样写代码。那些脏单就当脏单,以后再解释。我认为这种格式对于一次性解释可能更好,但对于文档来说肯定更糟糕。

关于python - 从 python 2.7 中的字符串中提取多个 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20984241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com