一种方法:
- 拆分名称的列表(或根据您的语言筛选)根据特殊分拣桶中的成员资格分为两个列表;
- 根据您想要的顺序排列特殊名称列表;
- 按字典顺序排列第二个列表;
- 合并列表。
该方法应该适用于任何具有排序和列表或数组的名称以保存名称的语言。
在Python:
names=['Conan', 'Cary', 'Clarence', 'Cathy', 'Mike', 'Blake', 'Baron', 'Vaughan', 'Albert', 'Gabriel', 'Cathy']
specials=['Mike', 'Cathy', 'James', 'Albert', 'Austin']
# split the lists.
n1=[n for n in names if n in specials] # ifilter would also work in Python
n2=[n for n in names if n not in specials]
# sort the first list based on order of specials, second lexicographically and combine:
print sorted(n1, key=lambda n:specials.index(n))+sorted(n2)
打印:
['Mike', 'Cathy', 'Cathy', 'Albert', 'Baron', 'Blake', 'Cary', 'Clarence', 'Conan', 'Gabriel', 'Vaughan']
一个改进是:
- 创建包括否定整数的用于索引的两个元件的数据元素作为第一个元素放入特殊列表/数组中和第二个元素的名字;
- 根据基于该元素的键或自定义
cmp
函数对列表/数组进行排序。
在Python中,您将在关键函数中使用元组。在C中,你会编写一个自定义的cmp函数。有了这个,您可以根据您的语言特点对names
进行排序。
元组中的两个元素将是特殊名称中的名称的否定索引(针对基于零的索引进行调整),然后是名称。如果非零,元组的第一个元素将胜出第二个元素。由于第一个元素是整数,因此即使specials
中有超过10个名称,它也会正确排序。
同样,在Python:
def cf(n):
rtr=(specials.index(n)-len(specials)-1 if n in specials else 0, n)
print rtr # to show what is being generated for the sort key...
return rtr
names.sort(key=cf) # sorts inplace
打印:
(0, 'Conan')
(0, 'Cary')
(0, 'Clarence')
(-5, 'Cathy')
(-6, 'Mike')
(0, 'Blake')
(0, 'Baron')
(0, 'Vaughan')
(-3, 'Albert')
(0, 'Gabriel')
(-5, 'Cathy')
现在names
已经整理就地和一个通到:
['Mike', 'Cathy', 'Cathy', 'Albert', 'Baron', 'Blake', 'Cary', 'Clarence', 'Conan', 'Gabriel', 'Vaughan']
你说这些名字应该保留在列表中,所以不应该以'Cathy Mike Albert Cathy'开头吗? – IVlad
@对不起,对不起。我的意思是特殊名字保留他们的“麦克凯西詹姆斯阿尔伯特奥斯汀”的秩序,他们作为一个整体应该在其他非特殊名称之前。 – Chris
“和*保留*他们的订单*为*” - 它要么保留或作为。请澄清。 –