Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert elements of a list into another list depending on date value?

I have a list of homes :

list1 = [home1, home2, home3, home4]

and I have another list of specific homes:

list2 = [ home6, home7, home8, home10]

Every home has a field date .I want to insert List2 into list1 depending on home.date

For example if home7.date < home1.date, so home7 will be inserted into list1 before home1

I tried to use two for loops but it seems to be very slow and there are many calculations done by the CPU

        for el in list1:
            for elt2 in list2:
                if el.date > elt2.date:
                    list1.insert((list1.index(el)),elt2)

PS : some dates are not set so they have a None value and I don't want to change the index of corresponded home in list1

Any ideas ?

like image 787
pietà Avatar asked Nov 19 '25 07:11

pietà


1 Answers

First thing first: modifying a list (or dict, set etc) while iterating over it is usually a very bad idea.

In your case, the simplest solution is probably to just merge the two lists first then sort the list using the key callback:

list1.extend(list2)
list1.sort(key=lambda x: x.date)
like image 54
bruno desthuilliers Avatar answered Nov 20 '25 19:11

bruno desthuilliers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!