如何解决Python从文本文件和总数中提取数字
我有一个名为cart.txt的简单.txt文件,该文件包含4行文本和数字,并以逗号分隔,即
23453,1,45.64,白色,手套
25753,2,78.32,红色,包
23346,1,24.54,蓝色,俱乐部
87653,4,76.12,绿色,球
我需要提取价格,然后加总。到目前为止,我有:
delta
运行程序时,我收到一条错误消息,指出python无法将str转换为浮点数:“,”。
如果我删除零件,数量等并在包含line.split的那一行上打印,我将收到全部4个价格,但结尾没有逗号。为什么python重新添加逗号,不允许我将其转换为float?非常感谢您的帮助。
解决方法
您正在做destructuring assignments
,并同时从list
中按索引获取项目
part,quantity,price,desc1,desc2 = line.split(",")[2]
假设string
是文件的内容。
string = '''
23453,1,45.64,white,gloves
25753,2,78.32,red,bag
23346,24.54,blue,club
87653,4,76.12,green,ball
'''
lines = string.strip().split('\n')
prices = []
for line in lines:
_,_,*_ = line.split(",")
prices.append(float(price))
print(sum(prices))
,
过滤所有价格,将它们附加在列表中,然后对列表求和,例如:
with open("cart.txt","r") as text_file:
all_the_price = [float(line.split(",")[2]) for line in text_file]
total = sum(all_the_price)
print(total)
,
parts = []
quantities = []
prices = []
descs1 = []
descs2 = []
with open("cart.txt","r") as text_file:
for line in text_file:
part,desc2 = line.strip().split(",")
parts.append(part)
quantities.append(quantity)
prices.append(float(price))
descs1.append(desc1)
descs2.append(desc2)
total = sum(prices)
print("The total price for the awesome Fathers Day gifts you bought is ${}".format(total))
这绝不是实现我认为的目标的最有效方法,但它应该可以帮助您了解此处所犯的错误。
您每次在另一行中阅读时都覆盖price
。
在这里,我创建了一堆额外的列表,当您通读文件时,将每条额外的数据附加到适当的列表中,然后求和在最后很简单。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。