Sort a sublist of elements in a list leaving the rest in place

前端 未结 15 2270
小蘑菇
小蘑菇 2021-02-13 14:28

Say I have a sorted list of strings as in:

[\'A\', \'B\' , \'B1\', \'B11\', \'B2\', \'B21\', \'B22\', \'C\', \'C1\', \'C11\', \'C2\']

Now I wan

15条回答
  •  礼貌的吻别
    2021-02-13 14:46

    If the elements that are to be sorted are all adjacent to each other in the list:

    You can use cmp in the sorted()-function instead of key:

    s1=['A', 'B' , 'B1', 'B11', 'B2', 'B21', 'B22', 'C', 'C1', 'C11', 'C2']
    
    def compare(a,b):
        if (a[0],b[0])==('B','B'): #change to whichever condition you'd like
            inta=int(a[1:] or 0)
            intb=int(b[1:] or 0)
            return cmp(inta,intb)  #change to whichever mode of comparison you'd like
        else:
            return 0               #if one of a, b doesn't fulfill the condition, do nothing
    
    sorted(s1,cmp=compare)
    

    This assumes transitivity for the comparator, which is not true for a more general case. This is also much slower than using key, but the advantage is that it can take context into account (to a small extent).

    If the elements that are to be sorted are not all adjacent to each other in the list:

    You could generalise the comparison-type sorting algorithms by checking every other element in the list, and not just neighbours:

    s1=['11', '2', 'A', 'B', 'B11', 'B21', 'B1', 'B2', 'C', 'C11', 'C2', 'B09','C8','B19']
    
    def cond1(a):           #change this to whichever condition you'd like
        return a[0]=='B'
    
    def comparison(a,b):    #change this to whichever type of comparison you'd like to make
        inta=int(a[1:] or 0)
        intb=int(b[1:] or 0)
        return cmp(inta,intb)
    
    def n2CompareSort(alist,condition,comparison):
        for i in xrange(len(alist)):
            for j in xrange(i):
                if condition(alist[i]) and condition(alist[j]):
                    if comparison(alist[i],alist[j])==-1:
                        alist[i], alist[j] = alist[j], alist[i]  #in-place swap
    
    n2CompareSort(s1,cond1,comparison)
    

    I don't think that any of this is less of a hassle than making a separate list/tuple, but it is "in-place" and leaves elements that don't fulfill our condition untouched.

提交回复
热议问题