您可以通过按位置排序并以相反的顺序申请来做到这一点。打领带时顺序重要吗?然后只按位置排序,而不是按位置和顺序排序,这样它们就会以正确的顺序插入。例如,如果插入 999@1 然后是 888@1,如果你对这两个值进行排序,你会得到 888@1,999@1。
12345
18889992345
但是仅按位置进行排序并使用稳定排序给出 999@1,888@1
12345
1999888345
这是代码:
import random
import operator
# Easier to use a mutable list than an immutable string for insertion.
sequence = list('123456789123456789')
insertions = '999 888 777 666 555 444 333 222 111'.split()
locations = [random.randrange(len(sequence)) for i in xrange(10)]
modifications = zip(locations,insertions)
print modifications
# sort them by location.
# Since Python 2.2, sorts are guaranteed to be stable,
# so if you insert 999 into 1, then 222 into 1, this will keep them
# in the right order
modifications.sort(key=operator.itemgetter(0))
print modifications
# apply in reverse order
for i,seq in reversed(modifications):
print 'insert {} into {}'.format(seq,i)
# Here's where using a mutable list helps
sequence[i:i] = list(seq)
print ''.join(sequence)
结果:
[(11, '999'), (8, '888'), (7, '777'), (15, '666'), (12, '555'), (11, '444'), (0, '333'), (0, '222'), (15, '111')]
[(0, '333'), (0, '222'), (7, '777'), (8, '888'), (11, '999'), (11, '444'), (12, '555'), (15, '666'), (15, '111')]
insert 111 into 15
123456789123456111789
insert 666 into 15
123456789123456666111789
insert 555 into 12
123456789123555456666111789
insert 444 into 11
123456789124443555456666111789
insert 999 into 11
123456789129994443555456666111789
insert 888 into 8
123456788889129994443555456666111789
insert 777 into 7
123456777788889129994443555456666111789
insert 222 into 0
222123456777788889129994443555456666111789
insert 333 into 0
333222123456777788889129994443555456666111789