Filter list of tuples in Python

martian_rover

I am trying to filter list of tuples with two conditions if tuple value is greater than 0.3 and there should not be more than 5 elements picked if first condition satisfies but not able to fit both.

List of tuples:

list_of_tuple = [(254, 0.9637927264127298),
 (354, 0.8522503527571762),
 (32, 0.7816368211562529),
 (165, 0.7545730507118511),
 (65, 0.730523154567809),
 (223, 0.6863456501573775),
 (263, 0.6630003543540749),
 (357, 0.6322069100774286),
 (383, 0.6134476413586814),
 (252, 0.5608248345843365),
 (31, 0.5123749051906423),
 (347, 0.466326739057893),
 (486, 0.3487919085343739),
 (54, 0.29397783822097),
 (257, 0.23987209993003836),
 (92, 0.22892930134708775),
 (7, 0.20977065219601607),
 (166, 0.19997039737766586),
 (145, 0.15806269571615644),
 (463, 0.1455164252456856),
 (139, 0.14485058856127903),
 (302, 0.14029875929667127),
 (320, 0.12460879531407618),
 (141, 0.12100147679918186),
 (350, 0.12007000240833345)]

Expected Result: (As there are more than 5 values here if first condition (>=0.3) satisfies), So get top 5 only

a = [(254, 0.9637927264127298),
 (354, 0.8522503527571762),
 (32, 0.7816368211562529),
 (165, 0.7545730507118511),
 (65, 0.730523154567809)]

I tried

a = [item  for item in list_of_tuple if (item[1]>=0.3) and len(list_of_tuple)<=5]

but it returns an empty list.

Grismar

Is this what you're after?

result = list(filter(lambda x: x[1] >= 0.3, list_of_tuple))[:5]
print(x)

Note that this isn't optimal if your list is very long, since the entire list is generated.

This is better for really large lists:

from itertools import islice

result = list(islice(filter(lambda x: x[1] >= 0.3, list_of_tuple), 5))
print(result)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related