我正在处理这个文本文件
Widget1
partA 2
partB 8
partC 4
Widget2
partD 30
partB 92
Widget3
partA 1
partB 1000
partC 500
partD 450
Widget4
partA 49
partC 100
partD 97
Widget5
partA 10
partD 20
我想为每个小部件添加所有部件数量,因此输出将是 “小部件1需要14个部件 小部件2需要122个部件”等。我无法跟踪到各自小部件的数量总和。thx提前。这是我到目前为止得到的
widgetfile = open("widgets.txt", "r", encoding="utf-8")
i=0
parttotal=0.0
quantities=[]
widgetdict={}
for line in widgetfile:
if "Widget" in line:
widget.append(line)
if "part" in line:
substring=line.split(" ")
quantities.append(substring[1])
现在,您正在将所有数量添加到一个大列表中,然后无法区分哪些数量属于哪个小部件。相反,您可以动态地添加这些值,当您运行到下一个“Widget”行(或文件末尾)时,您就知道您已经完成了该Widget
此外,我建议在完成后使用
with
自动关闭文件:请注意,我们如何在完成单个小部件后立即重置总计数,以及我们如何不必跟踪单个数量(或在多个小部件的任何点)
相关问题 更多 >
编程相关推荐