我正在使用此文本文件
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])
答案 0 :(得分:1)
现在,您将所有数量添加到一个大清单中,然后无法区分哪个数量属于哪个小部件。相反,你可以动态地添加值,当你遇到下一个“Widget”行(或文件的末尾)时,你知道你已经完成了这个小部件。
另外,我建议您在完成后使用with
自动关闭文件:
with open("widgets.txt", "r", encoding="utf-8") as widgetfile:
current_total = 0
current_widget = None # We don't have a widget yet
for line in widgetfile:
if "Widget" in line:
# Output the current widget here, if there is one
if current_widget != None:
print("{} needs {} parts".format(current_widget, current_total))
# Now store the new widget's name and reset the count
current_widget = line
current_total = 0
elif "part" in line:
# Take the second part of the line, convert it to a number
# and add it to the current total
current_total += int(line.split()[1])
# The loop is now done, but we haven't printed the last widget yet
if current_widget != None:
print("{} needs {} parts".format(current_widget, current_total))
请注意我们如何在完成单个小部件后立即重置总计数,以及我们如何甚至不必跟踪单个数量(或者在多个小部件的任何位置)。