根据条件过滤元组列表

For a given list of tuples, if multiple tuples in the list have the first element of tuple the same - among them select only the tuple with the maximum last element.

For example:

sample_list = [(5,16,2),(5,10,3),(5,8,1),(21,24,1)]

sample_list上面,因为5在这种情况下前 3 个元组具有相似的第一个元素,其中只有第二个元组应该保留,因为它具有最大的最后一个元素 => 3

预期操作:

op = [(5,10,3),(21,24,1)]

代码:

op = []
for m in range(len(sample_list)):
    li = [sample_list[m]]
    for n in range(len(sample_list)):
        if(sample_list[m][0] == sample_list[n][0]
           and sample_list[m][2] != sample_list[n][2]):
            li.append(sample_list[n])
    op.append(sorted(li,key=lambda dd:dd[2],reverse=True)[0])

print (list(set(op)))

这有效。但是对于长列表来说非常慢。有没有更pythonic或更有效的方法来做到这一点?

回答

您可以使用defaultdict对具有相同第一个元素的元组进行分组,然后根据第三个元素取每个组的最大值:

from collections import defaultdict
sample_list = [(5,16,2),(5,10,3),(5,8,1),(21,24,1)]
d = defaultdict(list)
for e in sample_list:
d[e[0]].append(e)
res = [max(val, key=lambda x: x[2]) for val in d.values()]
print(res)

输出

[(5, 10, 3), (21, 24, 1)]

这种做法是O(n)


以上是根据条件过滤元组列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>