所以我想在python 3中看起来像这样:
How many hours are in your sample? 7
Enter the count of cars for hour #1: 2
Enter the count of cars for hour #2: 5
Enter the count of cars for hour #3: 9
Enter the count of cars for hour #4: 11
Enter the count of cars for hour #5: 12
Enter the count of cars for hour #6: 6
Enter the count of cars for hour #7: 5
Hour #1: # #
Hour #2: # # # # #
Hour #3: # # # # # # # # #
Hour #4: # # # # # # # # # # #
Hour #5: # # # # # # # # # # # #
Hour #6: # # # # # #
Hour #7: # # # # #
Average: # # # # # # #
到目前为止我写过这个:
def main():
hourlist = number_cars()
graphic = hourlist
car_count_graphic_format(graphic)
def number_cars():
hours = input("How many hours are in your sample? ")
hours = int(hours)
hourlist = []
for i in range(hours):
hourcount = input("Enter the count of cars for hour #" +str(i+1)+ ": ")
hourcount = int(hourcount)
hourlist.append(hourcount)
hourlist.sort()
return hourlist
def car_average(car_count):
car_sum = 0
for position in range(len(car_count)):
car_sum = car_sum + car_count[position]
average = car_sum / len(car_count)
return average
def car_count_graphic_format(graphic):
for x in range(graphic):
graphic = "#" * graphic
print("Hour #:" ,graphic,)
main()
但每当我运行它时,它都有一个错误,老实说我在这一点上陷入困境。如果有人可以帮助我,我会非常感激!感谢任何能够帮助我的人!
答案 0 :(得分:1)
def car_count_graphic_format(graphic):
for x in range(graphic):
graphic = "#" * graphic
print("Hour #:" ,graphic,)
在这里你应该小心,你经常重复使用名称graphic
- 以解决不同的混淆问题。
该函数获取每小时的车辆计数列表,所以让我们调用该参数car_counts
。我们想为每个条目打印一行,因此我们必须迭代car_counts
中的元素。请注意,我们无法在此使用range(car_counts)
,因为car_counts
是一个列表但range()
需要一个数字。相反,我们可以直接遍历列表以在每次迭代中获取其中的每个元素。由于我们还想记下小时,我们使用enumerate()
来获取列表中元素的索引。由于小时从1开始,我们告诉enumerate()
从1开始计算:
for hour, count in enumerate(car_counts, start=1):
graphic = '# ' * count
print('Hour #{}: {}'.format(hour, graphic))
最后,我们还想找出平均值,所以我们计算汽车总数,然后再除以小时数(列表长度)来得到平均车数:
def car_count_graphic_format(car_counts):
total_cars = 0
for hour, count in enumerate(car_counts, start=1):
total_cars += count
graphic = '# ' * count
print('Hour #{}: {}'.format(hour, graphic))
average = round(total_cars / len(car_counts))
graphic = '# ' * average
print('Average: {}'.format(graphic))
最后请注意,您不想要对hourlist
功能中的number_cars
进行排序,否则您将丢失车辆计数属于哪个小时的信息。