【问题标题】:Pythonic way to get the max difference between any 2 consecutive elements of a list [duplicate]获取列表中任意两个连续元素之间最大差异的 Pythonic 方法[重复]
【发布时间】:2019-12-13 22:34:55
【问题描述】:

我有一个列表,其中存储了一场比赛的得分。在每个索引处,分数都会被存储,使其等于该轮(包括该轮)得分的总分。

  • 本轮第1-5分得分
  • 第2轮-本轮得3分
  • 第 3 轮 - 本轮得分 7 分
  • 第4轮-本轮得4分

这将导致

total_score = [5, 8, 15, 19]

我怎样才能将其巧妙地转换为一个列表,其中包含每个索引处的每一轮得分,而不是该轮的总得分。

所以我想把上面的列表变成:

round_scores = [5, 3, 7, 4]

仅仅迭代它并从当前索引的分数中减去前一个索引的分数并不是特别难。但是有没有更简洁的方法来做到这一点?也许是一个单行列表理解?我对 Python 还很陌生,但我在其他答案中看到了一些魔术在一行中完成。

【问题讨论】:

  • res = [total_score[0]] + [x-y for x, y in zip(total_score[1:], total_score[:-1])] 可能还有更漂亮的解决方案
  • a = np.array(total_score) 然后a[1:] -= a[:-1] 是一个很好的解决方案(很遗憾不是我的)
  • 这是一个非常好的解决方案,我只希望它适用于常规列表,因为创建该数组所需的时间比随后的实际解决方案要长。

标签: python list list-comprehension


【解决方案1】:

您可以将zip 与列表理解一起使用:

[total_score[0]] + [abs(x - y) for x, y in zip(total_score, total_score[1:])]

示例

total_score = [5, 8, 15, 19]

print([total_score[0]] + [abs(x - y) for x, y in zip(total_score, total_score[1:])])
# [5, 3, 7, 4]

【讨论】:

  • 或较小的字节数res = [x-y for x, y in zip(total_score, [0]+total_score)]
  • 另外,我不会接受abs。如果您得分为负分,则必须如此显示(并且您始终可以颠倒zip 的顺序)。
【解决方案2】:

您可以只遍历索引:

round_score = [total_score[0]]
round_score += [total_score[i] - total_score[i-1] for i in range(1, len(total_score))]

或者在一个表达式中进行一点预处理:

temp = [0] + total_score

round_score = [temp[i] - temp[i-1] for i in range(1, len(temp))]

【讨论】:

    【解决方案3】:
    x = [5, 8, 15, 19]  # total scores
    y = [x[i] - x[i-1] if i else x[i] for i in range(len(x))]  # round scores
    print(y)
    # output
    [5, 3, 7, 4]
    

    【讨论】:

      【解决方案4】:

      使用 numpy,

      import numpy as np
      
      total_score = [5, 8, 15, 19]
      round_scores = np.diff(total_score, prepend=0)
      

      【讨论】:

      • 不错的解决方案-我建议您将其添加到标记的副本中!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 2014-02-15
      • 2019-11-26
      • 2017-06-24
      • 1970-01-01
      • 2011-03-28
      相关资源
      最近更新 更多