按复杂条件排序

时间:2015-05-26 07:20:40

标签: python django

Model1(models.Model):
  name = models.CharField(max_length=30)


Model2(models.Model):
  model1 = models.ManyToManyField(FontClass) 

res = Model1.objects.all().filter(....).order_by('model1__name....???')

如何通过更复杂的条件对结果进行排序,例如model1__name名称中是否有下划线?例如,Model1.objects.all().filter(....)返回以下名称:

aaa_bbb
aaaccc
aaa_ttt
aaa_ddd
ggggg
yyy_cccc
zzz_kkk
dddd

排序后应该是:

aaa_bbb
zzz_kkk
aaa_ddd
aaa_ttt
yyy_cccc

aaaccc
ggggg
dddd

首先是名字中带有下划线的,然后是 - 没有它。

请注意,条件只是一个例子,我希望按即使是复杂的方式进行排序,我只是想知道如何做到这一点。

2 个答案:

答案 0 :(得分:0)

如何更改常规排序算法的比较功能?

def comp(a, b):
    if a>b:
        return True

def mergeSort(alist):
    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0
        while i<len(lefthalf) and j<len(righthalf):
            if comp(righthalf[j], lefthalf[i]):
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1

        while i<len(lefthalf):
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1

        while j<len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1

my_list = [10,4,2,5,1]
mergeSort(my_list)
print my_list

只需更改“comp”功能即可。

答案 1 :(得分:0)

您可以使用import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { static int maxXor(int l, int r) { String p = " "; String q = " "; String s = " "; int sum = 0; do { p = (l % 2) + p; q = (r % 2) + q; l = l / 2; r = r / 2; } while ((l > 0) && (r > 0)); int n = Integer.valueOf(p); int m = Integer.valueOf(q); while ((n != 0) && (m != 0)) { if ((n % 10) == (m % 10)) { s = s + "0"; } else { s = s + "1"; } } System.out.println(s); int len = s.length(); int x = Integer.parseInt(s); for (int i = 1; i <= len; i++) { int d = x % 10; sum = (sum * 10) + d; x = x / 10; } return sum; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int res; int _l; _l = Integer.parseInt(in.nextLine()); int _r; _r = Integer.parseInt(in.nextLine()); res = maxXor(_l, _r); System.out.println(res); } } 的{​​{1}}方法应用数据库排序

extra

请注意,您将绑定到特定数据库。我的例子是在postgresql上工作。