這裏有一個解決方案:在
sorted_fullset = ["a","b","c","d","e","f"]
sorted_subset = ["a","b","e"]
def shuffle_set_by_subset(sorted_fullset,sorted_subset,shuffled_subset):
shuffle = dict((item,idx) for idx,item in enumerate(sorted_subset))
shuffled_fullset = sorted_fullset[:]
for idx,item in enumerate(sorted_fullset):
if item in sorted_subset:
place_in_sorted_subset = shuffle[item]
shuffled_fullset[idx] = shuffled_subset[place_in_sorted_subset]
return shuffled_fullset
print shuffle_set_by_subset(sorted_fullset,sorted_subset,["e","b","a"])
print shuffle_set_by_subset(sorted_fullset,sorted_subset,["a","e","b"])
結果:
['e', 'b', 'c', 'd', 'a', 'f']
['a', 'e', 'c', 'd', 'b', 'f']
謝謝。我有效地做到了這一點,但沒有明確使用額外的數組。我有原始數組A = {a,b,c,d,e,f},原始子集B = {b,d,e}。子集獲得C = {d,e,b}。然後我設置了兩個指針,一個指向原始數組pA,另一個指向子集pC。然後我開始按照以下規則遞增A設置項目:如果項目pA指向不在C中,則保留原位並提前pA。如果pA項目在C中,則插入pC指向的項目並增加pA和pC。 – seanm
不能完全讓你滿意,但很高興你把它整理出來。指針可能會很棘手。也做測試重複的信件! –