Python:从文本中拆分数字然后求和

标签 python

我有一个格式如下的文本文件,我将其导入 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

解释:

  1. 为了对项目进行计数,我们使用了一个集合来获取唯一计数。如果您想要全部,请改用列表。
  2. 我们通过按美元符号拆分从列表中提取数字来计算总和。

关于Python:从文本中拆分数字然后求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092497/

相关文章:

python - 导入已安装的模块时为 "ImportError: DLL load failed: The specified module could not be found"

python - Selenium :WAITING元素可点击不工作

python - 定位没有 id 或 class 属性的表

python - ansible正则表达式替换所有匹配的string1,排除string2

python XML : write "instead of &quot

python - 在python中添加分隔符

python - Matplotlib:一条线,以不同单位绘制在两个相关的 x 轴上?

python - 在理解中引用类变量时出现名称错误

python - 如何运行超过 10 万个任务的 Airflow dag?

Python:在单个模块上使用 Sphinx 生成 autodoc?