要明确的是,我并不是要求任何人为我做这件事。我只是问了一个问题,寻求指导,这样我就可以继续工作了。
我们得到了一个文件,其中给出了不同重量的包裹;
11
25
12
82
20
25
32
35
40
28
50
51
18
48
90
我必须创建一个程序来计算包裹的数量,将它们分类为Small、Medium和Large,并找到重量的平均值。我知道我必须使用If语句和for循环来累积权重计数,并在每个类别中对它们进行分类。
"小"、"中"one_answers"大"的术语如下;
小型<10磅
中等>=10磅并且<30磅
大型>=30磅
如果没有重量的包裹如果输入了类,则报告消息"N/A"而不是平均值(如果您尝试除以0会得到一个异常(。
这是我到目前为止的代码,我不知道是否必须在if、elif和else之后包含for循环。或者如果我所拥有的一切步入正轨。
infile = open("packages.txt", 'r')
count = 0
line = infile.readline()
weight = int(line)
for line in infile:
if weight < 10:
count = count + 1
weight = weight + int(line)
while weight < 10:
try:
avg = weight / count
except ValueError:
print("N/A")
elif weight >= 10:
if weight < 30:
weight = weight + int(line)
count = count + 1
avg = weight/count
else:
weight = weight + int(line)
count = count + 1
avg = weight/count
输出必须看起来像这个
Category Count Average
Small 0 N/A
Medium 7 19.9
Large 8 53.5
同样,我不想找人为我做这件事。我正在寻找下一步和/或调整,以使我能够继续前进。非常感谢。
在处理文件对象时,我认为最好使用with
语句。这样做的优点是,即使在处理过程中出现异常,文件套件完成后也会正确关闭。
换句话说,您不需要在文件对象上调用close()
方法,并且您确信在发生异常的情况下,会关闭引发。
所以
infile = open("packages.txt", 'r')
#operations on file
...
infile.close()
使用会更好
with open("packages.txt",'r') as infile:
#following operation
#on infile like reading
平均计算
对于此操作,您可以使用字典。这是一个映射数据结构,是一组key,value
对,其中键需要是字符串(在您的情况下是"小"、"中"、"大"(,值可以是简单类型或其他数据结构,如列表、字典或对象。
在读取文件时,您将使用基于if条件的权重填充列表,最后您可以使用空闲列表并使用sum((和len((计算平均值。
packages = {"small": [],
"medium": [],
"large": []}
with open("packages.txt","r") as packs:
for pack in packs:
weight = int(pack)
if weight < 10:
packages["small"].append(weight)
elif weight < 30:
packages["medium"].append(weight)
else:
packages["large"].append(weight)
###Printing the the average###
table_row = "%st%it%s" # string for formatting output, not the best solution
for key,weights in packages.items():
print(table_row % (key, len(weights), averageValues(weights)))
其中averageValues()
是下面的函数,它计算平均值,并像字符串一样返回我们想要的小数位数。
def averageValues(values,decimals=1):
float = "%." + str(decimals) + "f"
try:
avg = sum(values)/len(values)
return float % avg
except:
return "N/A"
阅读这个问题的答案,了解如何获得字典的有序表示,即无序的数据结构。
首先,您需要三个weight
和count
变量:每个类别一个。
那么你对文件的阅读有点缺陷。不要从读一行开始,而是让循环并在循环中分配给weight
,这是你做的第一件事
也许是这样的:
total_small = 0
total_medium = 0
total_large = 0
count_small = 0
count_medium = 0
count_large = 0
for line in infile:
weight = int(line)
if weight < 10:
total_small += weight
count_small += 1
# And the same for medium and large as well...
然后在循环之后,您可以在打印时轻松计算每个类别的平均值。
哦,而且你没有检查中等包装的上限,这是你需要做的。
维护3个变量来计算3个范围,如weight1Sum,weight2Sum,weight3Sum
,并在第一个像weight1Sum=0 一样将其初始化为零
您的count
变量是可以的。当它在范围内时,您需要添加权重值。然后u可以将计数除以相关的weightSum来显示相关值。
通常,你需要根据范围保持3个权重并更新它。