假设我有一个这样的列表:[2, 3, 3, 2, 1, 1]
,我想对其进行排序以获得[1, 1, 3, 3, 2, 2]
。我如何以良好的pythonic方式做到这一点?我已经这样尝试过:
import random
alist = [1, 1, 2, 2, 3, 3]
random.shuffle(alist)
print(alist)
ones = []
twos = []
threes = []
for item in alist:
if item == 1:
ones.append(item)
elif item == 2:
twos.append(item)
else:
threes.append(item)
ordered_list = []
ordered_list.extend(ones)
ordered_list.extend(threes)
ordered_list.extend(twos)
print(ordered_list)
但是我想这不是最好的方法。也许有更好的方法?
答案 0 :(得分:4)
您可以创建一个保存项目顺序的字典,然后对它进行查找,作为常规sort()
方法的关键参数。
orderlist = [1, 3, 2]
order = {item: prio for prio, item in enumerate(orderlist)}
# order = {1:0, 3:1, 2:2}
alist = [1, 2, 3, 3, 2, 1]
alist.sort(key=lambda i: order[i])
alist
输出
[1, 1, 3, 3, 2, 2]