合并列表的最有效方法,其中最终值是每个列表维护位置的最大值 [英] Most efficient way to merge lists where the final values are the max from each list maintaining position

查看:72
本文介绍了合并列表的最有效方法,其中最终值是每个列表维护位置的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将这些列表合并到一个单个列表(其中最终值是每个列表保持位置的最大值)的最有效方法是什么?现在,我正在对所有列表进行蛮力迭代,并在最终列表中设置最大值.它可以工作,但是效率不高,因为我的数据集很大.关于如何提高效率的任何想法?

What's the most efficient way to merge these lists into one single list where the final values are the max from each list maintaining position? Right now I'm doing a brute force iteration over all of the lists and setting the max value in the final list. It works but it's not very efficient since my data sets are massive. Any ideas on how to make this more efficient?

graph1 = [[0, 0, 0], [1, 0, 1], [2, 0, 0]]
graph2 = [[5, 0, 0], [1, 0, 1], [2, 0, 0]]
graph3 = [[2, 1, 0], [0, 0, 1], [0, 0, 0]]
graph4 = [[1, 0, 1], [9, 0, 0], [2, 0, 0]]

graphs = [graph1, graph2, graph3, graph4]

# TODO, what's the most efficient way to merge these lists into one single list where the final values are the max from each list maintaining position?
# desiredResultGraph = [[5, 1, 1], [9, 0, 1], [2, 0, 0]]


基于以下Mark Meyer的解决方案更新了解决方案:

graph = np.ndarray(shape=(4, 3, 3), dtype=float, order='F')
graph[0] = [[0, 0, 1], [1, 0, 1], [2, 0, 0]]
graph[1] = [[0, 0, 1], [1, 0, 1], [2, 0, 0]]
graph[2] = [[5, 0, 0], [1, 0, 1], [2, 0, 0]]
graph[3] = [[2, 1, 0], [9, 0, 1], [0, 0, 0]]

PrintAndLog("graph of type " + str(type(graph)) + " = " + str(graph))

resultGraph = graph.max(axis=0)
PrintAndLog("resultGraph of type " + str(type(resultGraph)) + " = " + str(resultGraph))

输出:

graph of type <class 'numpy.ndarray'> = 
[[[ 0.  0.  1.]
  [ 1.  0.  1.]
  [ 2.  0.  0.]]

 [[ 0.  0.  1.]
  [ 1.  0.  1.]
  [ 2.  0.  0.]]

 [[ 5.  0.  0.]
  [ 1.  0.  1.]
  [ 2.  0.  0.]]

 [[ 2.  1.  0.]
  [ 9.  0.  1.]
  [ 0.  0.  0.]]]
resultGraph of type <class 'numpy.ndarray'> = 
[[ 5.  1.  1.]
 [ 9.  0.  1.]
 [ 2.  0.  0.]]

推荐答案

如果要处理大量数字数据,将很难击败Numpy的性能.它使这样的事情变得容易:

If you are manipulating large sets of numeric data, you will be hard-pressed to beat the performance of Numpy. And it makes things like this easy:

import numpy as np

graph1 = [[0, 0, 0], [1, 0, 1], [2, 0, 0]]
graph2 = [[5, 0, 0], [1, 0, 1], [2, 0, 0]]
graph3 = [[2, 1, 0], [0, 0, 1], [0, 0, 0]]
graph4 = [[1, 0, 1], [9, 0, 0], [2, 0, 0]]

np.array([graph1, graph2, graph3, graph4]).max(axis = 0)

结果:

array([[5, 1, 1],
       [9, 0, 1],
       [2, 0, 0]])

这篇关于合并列表的最有效方法,其中最终值是每个列表维护位置的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆