数组中图的组合点?

我已经从网络抓取工具中收集了数据,并希望以此绘制折线图。 在我的点列表中[[[1,4],[2,3],[3,8 ......]),有一些点在“ x”上彼此重叠,但在“ y”上具有不同的值'。这些应合并为一个(平均值)。

[[2,3],[5,2],[3,4],4]...] ----------> [[2,4]...]

有没有比循环更有效的方法了?

fish890129 回答:数组中图的组合点?

您只能遍历这些内容,但是我们对此可能会很Python。这是我想出的解决方案:

from itertools import groupby
from operator import itemgetter
from statistics import mean
inp = [[2,3],[5,2],[3,4],4]]

points = [(x,mean(map(itemgetter(1),g))) for x,g in groupby(sorted(inp,key=itemgetter(0)),key=itemgetter(0))]
print(points)  # [(2,3),(3,4),(5,3)]

我们可以将此列表理解分解为以下等效代码:

points = []
inp.sort(key=itemgetter(0))                   # Sort results by 'x' value (for groupby)
for x,g in groupby(inp,key=itemgetter(0)):  # Iterate through all grouped x values
    y = map(itemgetter(1),g)                 # Extract all the 'y' values into a list
    avg_y = mean(y)                           # Get the statistical mean of all the 'y'
    points.append((x,avg_y))                 # Add this x,y-coordinate to the result set
本文链接:https://www.f2er.com/2851635.html

大家都在问