【问题标题】:Python university exam,Python大学考试,
【发布时间】:2018-05-10 16:12:23
【问题描述】:

我必须创建一个函数来计算不同生产线在一段时间内生产的产品的平均值。

示例:

input = [('line1', 0, 5), ('line1', 0, 6), ('line2', 0, 3), ('line1', 0, 5), ('line3', 0, 4), ('line2', 0, 9), ('line3', 0, -1), ('line2', 0, 9), ('line2', 0, 10), ('line3', 0, 12), ('line1', 0, 1), ('line3', 0, 16)]

output = {'line1': 4.25, 'line2': 7.75, 'line3': 7.75}

我无法计算每行的平均值,因为我不知道如何确定两天之间的时间段。

编辑:对不起,我想我没有很好地解释这个问题。这不是一个实际的考试,这是我的教授之前给我培训的考试。

【问题讨论】:

  • 请添加您尝试过的内容。另外,第 1 行得到 4.25 的实际计算是什么?
  • 时间范围在哪里起作用?从输出来看,您似乎只需要每行的平均值。

标签: python python-3.x python-requests


【解决方案1】:

我希望这不是针对真正的“考试”,因为在考试问题上寻求外部帮助通常违反了学校的荣誉守则,但我会为您提供疑问。

我写了这个非常简单的版本,因为你是 Python 新手,应该相对容易理解每​​一行的逻辑。

data = [('line1', 0, 5), ('line1', 0, 6), ('line2', 0, 3), ('line1', 0, 5), ('line3', 0, 4), ('line2', 0, 9), ('line3', 0, -1), ('line2', 0, 9), ('line2', 0, 10), ('line3', 0, 12), ('line1', 0, 1), ('line3', 0, 16)]

results = {}

for item in data:
  line = item[0]
  if not line in results:
    results[line] = {}
    results[line]["count"] = 1
    results[line]["total"] = item[2]
  else:
    results[line]["count"] += 1
    results[line]["total"] += item[2]

averaged_results = {}

for line in results:
  averaged_results[line] = results[line]["total"] / float(results[line]["count"])

print(averaged_results) 

您可以run this code 验证它是否有效并对其进行重构。有一些更简洁、更高效的“更好”方法,但此解决方案是为初学者设计的。

【讨论】:

    【解决方案2】:

    您需要按行对数据进行分组:

    import itertools
    input = [('line1', 0, 5), ('line1', 0, 6), ('line2', 0, 3), ('line1', 0, 5), ('line3', 0, 4), ('line2', 0, 9), ('line3', 0, -1), ('line2', 0, 9), ('line2', 0, 10), ('line3', 0, 12), ('line1', 0, 1), ('line3', 0, 16)]
    new_result = {a:[c for *_, c in b] for a, b in itertools.groupby(sorted(input, key=lambda x:x[0]), key=lambda x:x[0])}
    final_result = {a:round(sum(b)/float(len(b)), 2) for a, b in new_result.items()}
    

    输出:

    {'line1': 4.25, 'line3': 7.75, 'line2': 7.75}
    

    编辑:collections.defaultdict 的更简单选项:

    from collections import defaultdict
    d = defaultdict(list)
    for a, _, b in input:
      d[a].append(b)
    
    final_result = {a:round(sum(b)/float(len(b)), 2) for a, b in d.items()}
    

    输出:

    {'line1': 4.25, 'line3': 7.75, 'line2': 7.75}
    

    【讨论】:

    • 考虑到这个问题是初学者问的,我认为这个解决方案可能过于复杂。
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多