简体   繁体   中英

How to check if list item sits between tuples in another list?

I'm trying to return a pair of tuples in a list when an item in another list is numerically in-between them. I've looked through the site for help, but I haven't been able to find a solution that works/can be adapted for me.

Firstly consider the two lists below:

my_list = [1.5, 1.2, 1.1]
min_max = [(1.1, 1.4), (1.0, 1.3), (1.6, 1.8)]

I need each item in my_list to iterate through each pair of tuples in the min_max list, returning a pair when it sits within that range. Using the data from my_list , it would return:

(1.1, 1.4)
(1.0, 1.3)

Note that although both 1.2, and 1.1 both fall between (1.0, 1.3), I only need it to return once. Progress wise: I can iterate through a list when the range is fixed using the lambda function and I tried expanding it with list iteration, but I can't get it to work

list_return = filter(lambda x: 1.1 <= x <= 1.5, my_list)
[i for i in my_list]
print (list_return)

I've tried all sorts of variations, and i'm beginning to wonder if i'm approaching this correctly?

It seems like you are stuck trying to iterate through my_list , but this is simpler to iterate through min_max and check if any values in my_list are between each pair. This is working for me.

result = [(a, b) for a, b in min_max if any(a <= item <= b for item in my_list)]
print(result)

And I get

[(1.1, 1.4), (1.0, 1.3)]

You can do

my_list = [1.5, 1.2, 1.1]
min_max = [(1.1, 1.4), (1.0, 1.3), (1.6, 1.8)]
for i in[i for i in min_max if list(filter(lambda x: min(i) <= x <= max(i), my_list))]:
    print(i)

That will output

(1.1, 1.4)
(1.0, 1.3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM