Python在2D列表的第一列中找到重复项,并基于第二列删除其中一个

2024-04-19 16:26:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种从2D列表中删除重复项的方法,但是基于第二列中的最高值。我知道如何在几个for循环中完成,但我正在寻找一个O(N)解决方案。 样本输入:

inputLst = [[100,150]
          ,[150,140]
          ,[200,180]
          ,[300,150]
          ,[300,100]
          ,[320,180]]

输出应为:

^{pr2}$

这是我现在掌握的代码:

        SortLst = [[100,150],[150,140],[200,180],[300,150],[300,100],[320,180]]
        lst = []
        lastRow = SortLst[0]
        for row in SortLst+[0,0]:
            if row[0] != lastRow[0]:
                lst.append(lastRow)
                lastRow = row
            elif row [1] > lastRow[1]:
                lastRow =  row

排序依据:

SortLst = sorted(zip(self.WavelengthPanel.GetValues(col=1),self.Shuttertime))

Tags: 方法代码inself列表forif解决方案
1条回答
网友
1楼 · 发布于 2024-04-19 16:26:20

你可以看看这个

from pprint import pprint

input_lst = [[100, 150],
             [150, 140],
             [200, 180],
             [300, 150],
             [300, 100],
             [320, 180]]

output_lst = dict()

for n, v in input_lst:
    if n in output_lst:    # O(1)
        output_lst[n] = max(output_lst[n], v)    # O(1)
    else:
        output_lst[n] = v    # The question is, what is the complexity of this operation 

pprint(output_lst, width=10)

输出

^{pr2}$

您可以轻松地将输出转换为列表。在

相关问题 更多 >