我有一个对象列表。我只想对满足特定条件的值进行排序。考虑这个列表:
class Destination:
def __init__(self, name, tag):
self.name = name
self.tag = tag
dest = [
Destination(name="language", tag=['lang']),
Destination(name="operationId", tag=['order_02']),
Destination(name="eventTime", tag=['order_01']),
Destination(name="countryCode", tag=[]),
Destination(name="eventDate", tag=['order_00']),
Destination(name="offerId", tag=['primary_key'])
]
我想对其中包含
tag
的 order
值进行排序。结果应该如下所示:
output = [
Destination(name="language", tag=['lang']),
Destination(name="eventDate", tag=['order_00']),
Destination(name="eventTime", tag=['order_01']),
Destination(name="operationId", tag=['order_02']),
Destination(name="countryCode", tag=[]),
Destination(name="offerId", tag=['primary_key'])
]
目前,我可以使用
cols = sorted(dest, key=lambda x: x.tag)
对所有标签进行排序,但我需要一些帮助来重写它,以便仅对包含特定值的 tags
进行排序,同时保持其他值不变。如有任何帮助,我们将不胜感激!
假设您想要所有无序项,然后满足第一个顺序时所有已排序的顺序,然后是所有其他对象,您可以使用循环和列表来收集中间体:
def is_order(x):
return x.tag and x.tag[0].startswith('order')
orders = []
others = []
out = []
flag = True # directly add to "out" if True
for x in dest:
if is_order(x):
flag = False # start collecting in lists
orders.append(x)
elif flag:
out.append(x) # directly add to "out"
else:
others.append(x) # add to "others" temporarily
# add sorted "orders"
out.extend(sorted(orders, key=lambda x: x.tag))
# add others
out.extend(others)
输出:
[Destination(name=language, tag=['lang']),
Destination(name=eventDate, tag=['order_00']),
Destination(name=eventTime, tag=['order_01']),
Destination(name=operationId, tag=['order_02']),
Destination(name=countryCode, tag=[]),
Destination(name=offerId, tag=['primary_key'])]