我有一个格式如下的文本文件,我将其导入 Python:
hammer#9.95
saw#20.15
shovel#35.40
最终我想开发一个动态查询,允许我删除“#”符号并替换为“$”符号,然后将文本文件中的值相加/计算其中的项目数。我通过一些试验和错误想出了这个,但处理文本文件中的更改不是动态的:
# display header line for items list
print('{0: <10}'.format('Item'), '{0: >17}'.format('Cost'), sep = '' )
# add your remaining code below
with open('invoice.txt','rt') as infile:
for line in infile:
print("{:<21} {}".format(line.strip().split('#')[0],"$"+line.strip().split("#")[1]))
print(' ')
str1 = 'Total cost\t' +' ' + '$65.50'
print(str1)
str2 = 'Number of tools\t' + ' ' +'3'
print(str2)
有什么建议吗?提前感谢阅读。
最佳答案
您可以通过以下方式进行:
d = ['hammer#9.95', 'saw#20.15', 'shovel#35.40']
## replace hash
values = []
items = set()
for line in d:
line = line.replace('#', '$')
values.append(line.split('$')[1])
items.add(line.split('$')[0])
## sum values
sum(map(lambda x: float(x), values))
65.5
## count items
len(items)
3
解释:
- 为了对项目进行计数,我们使用了一个集合来获取唯一计数。如果您想要全部,请改用列表。
- 我们通过按美元符号拆分从列表中提取数字来计算总和。
关于Python:从文本中拆分数字然后求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092497/