When you use Python or Django to write some gadget applications, you may encounter the case of merging multiple lists into a list. Purely from a technical point of view, it is not difficult to deal with, can think of a lot of ways, but I think there is a very simple and efficient method is I have not noticed before. That is to use the chain method to merge multiple lists. It can also be used to merge Django's QuerySet.
#Coding:utf-8 fromItertoolsImportChaina= [1, 2,"AAA",{"name":"Roy"," Age": 100}]b= [3,4]c= [5,6]#items = a + B + CItems =chain (A,B,C) forIteminchItems:PrintItem
The output results are as follows:
aaa{'age 'name'Roy' }3456
This can be a good combination of success.
2. The Django always merges multiple queryset with chain.
If you want to merge multiple queryset of the same model in Django, you can do so in this way.
1 #Coding:utf-82 fromItertoolsImportchain3 fromYihaomen.common.modelsImportarticle4Articles1 = Article.objects.order_by ("autoid"). Filter (Autoid__lt = +). VALUES ('autoid','title')5Articles2 = Article.objects.filter (autoid =). VALUES ('autoid','title')6Articles = Articles1 | Articles2#Note the way it is used here. If the model is the same, and no slices are used, and the fields are the same7 Printarticles18 PrintArticles29 PrintArticles
This works well, but with some limitations, there are plenty of scenarios for Django, merging into a QuerySet and then returning to the template engine for processing.
Of course, you can also use chain to achieve, with chain to achieve will be more convenient, and not so many restrictions, even if the different model query out of the data, can be easily merged into a list.
1 #Coding:utf-82 fromItertoolsImportchain3 fromYihaomen.common.modelsImportarticle, UserID4Articles1 = Article.objects.order_by ("autoid"). Filter (Autoid__lt = +). VALUES ('autoid','title')5Users =UserID.objects.all ()6Items =Chain (articles1, users)7 forIteminchItems:8 PrintItem
This is more convenient and useful, and it is convenient to handle some lists that need to be merged and then transfer them to a certain place.
Original address: Merging multiple Python lists and merging multiple Django QuerySet, thanks to the original author for sharing.
Merging multiple python lists and merging multiple Django QuerySet methods