I want to find the all tuple items with the top 5 max values in a tuple list based upon the 2nd element of the tuple. For example, I have a tuple list
x1 = [(a, 5), (b, 5), (c, 4), (d, 3), (e, 8), (f, 9), (g, 2), (h, 1)]
I want to get the following list:
x2 = [(a, 5), (b, 5), (c, 4), (d, 3), (e, 8), (f, 9)]
As the top 5 unique values for 2nd elements are 9, 8, 5, 4, 3 and a, b both have value 5, they both should be included in the list.
Any idea on how to realize this? Thanks!
Find the top 5 second elements:
i = set(list({x[1] for x in x1})[-5:])
Filter the list:
x2 = list(filter(lambda x: x[1] in i, x1))
Or even better:
ss = {x[1] for x in x1}
if len(ss) > 5:
i = list(ss)[-5]
x2 = list(filter(lambda x: x[1] >= i, x1))
else:
x2 = x1
Output:
[('a', 5), ('b', 5), ('c', 4), ('d', 3), ('e', 8), ('f', 9)]
x1 = [('f', 9), ('e', 8), ('a', 5), ('b', 5), ('c', 4), ('d', 3), ('g', 2), ('h', 1)]
x1.sort(key=lambda x: x[1], reverse=True)
max5set = set()
i = 0
for _, num in x1:
max5set.add(num)
i += 1
if (len(max5set) == 6):
break
print(x1[:i-1])
output:
[('f', 9), ('e', 8), ('a', 5), ('b', 5), ('c', 4), ('d', 3)]
if you want to get this tuple list alphabetically, do
print(sorted(x1[:i-1], key=lambda x: x[0]))
output will be
[('a', 5), ('b', 5), ('c', 4), ('d', 3), ('e', 8), ('f', 9)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With