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

后端 未结 3 1794
孤独总比滥情好
孤独总比滥情好 2021-01-22 09:39

I have a list of homes :

list1 = [home1, home2, home3, home4]

and I have another list of specific homes:

list2 = [ home6, home7         


        
相关标签:
3条回答
  • 2021-01-22 10:24

    Edited:

    list3 = (list1 + list2)
    list3.sort(key = lambda x: x.date)
    
    0 讨论(0)
  • 2021-01-22 10:42

    To return a new sorted list, you should use the sorted() built-in function:

    sorted_list = sorted(list1 + list2, key=lambda x: x.date, reverse=True)
    
    0 讨论(0)
  • 2021-01-22 10:46

    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)
    
    0 讨论(0)
提交回复
热议问题