Python按多因素自定义排序

2024-04-27 17:09:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有这样一个(python)列表

my_list = [
    'Large Spearmint Bag Back',
    'Large Peppermint Bag Back',
    'Large Cinnamon Bag Back',
    'Small Peppermint Bag Front',
    'Medium Peppermint Bag Front',
    'Family Shot',
    'Large Cinnamon Bag Front',
    'Large Peppermint Bag Front',
    'Large Spearmint Bag Front',
]

您会注意到列表中有一些项集,比如Large Spearmint Bag FrontLarge Spearmint Bag Back,其中唯一的区别是一个是前面,一个是后面。我需要按字母顺序对这些文件进行排序,但要将前面的文件放在后面的文件之前,这样输出的文件就会如下所示:

[
    'Family Shot',
    'Large Cinnamon Bag Front',
    'Large Cinnamon Bag Back',
    'Large Peppermint Bag Front',
    'Large Peppermint Bag Back',
    'Large Spearmint Bag Front',
    'Large Spearmint Bag Back',
    'Medium Peppermint Bag Front',
    'Small Peppermint Bag Front'
]

我甚至不确定内置的sorted函数是否可以做到这一点。你能帮我解决这个问题吗?你知道吗


Tags: 文件列表mybackfamilylistsmallmedium
3条回答

一个简单的选择是在“Front”之前添加一个带有a的“special tag”,然后sort并删除“special tag”,“special tag”的原因是确保它不会在列表中的一个单词中重复。你知道吗

代码:

my_list = [
    'Large Spearmint Bag Back',
    'Large Peppermint Bag Back',
    'Large Cinnamon Bag Back',
    'Small Peppermint Bag Front',
    'Medium Peppermint Bag Front',
    'Family Shot',
    'Large Cinnamon Bag Front',
    'Large Peppermint Bag Front',
    'Large Spearmint Bag Front',
]

my_list_edit = ["{}A-tag{}".format(word[:word.rfind('Front')], 'Front') if 'Front' in word else word for word in my_list]

my_list_edit = sorted(my_list_edit)

my_list_edit = [word.replace('A-tag', '')for word in my_list_edit]

print my_list_edit 

输出:

['Family Shot',
 'Large Cinnamon Bag Front',
 'Large Cinnamon Bag Back',
 'Large Peppermint Bag Front',
 'Large Peppermint Bag Back',
 'Large Spearmint Bag Front',
 'Large Spearmint Bag Back',
 'Medium Peppermint Bag Front',
 'Small Peppermint Bag Front']
from operator import  itemgetter
lf = [
    'Family Shot',
    'Large Cinnamon Bag Front',
    'Large Cinnamon Bag Back',
    'Large Peppermint Bag Front',
    'Large Peppermint Bag Back',
    'Large Spearmint Bag Front',
    'Large Spearmint Bag Back',
    'Medium Peppermint Bag Front',
    'Small Peppermint Bag Front'
]

# find 'Family Shot', save into tuple, remove from list
ind_fam_shot = lf.index('Family Shot')
fam_shot=tuple(lf[ind_fam_shot].split())
lf.remove('Family Shot')

li = list(map(lambda x: tuple(x.split()),lf))

li =  sorted(li,key=itemgetter(1))
li.insert(0,fam_shot)

for el in li:
print(el)

('Family', 'Shot')
('Large', 'Cinnamon', 'Bag', 'Front')
('Large', 'Cinnamon', 'Bag', 'Back')
('Large', 'Peppermint', 'Bag', 'Front')
('Large', 'Peppermint', 'Bag', 'Back')
('Medium', 'Peppermint', 'Bag', 'Front')
('Small', 'Peppermint', 'Bag', 'Front')
('Large', 'Spearmint', 'Bag', 'Front')
('Large', 'Spearmint', 'Bag', 'Back')
sorted(my_list, key=lambda item: (item.split()[:-1], 'Back' in item))

item.split()[:-1]返回除最后一个单词外的所有单词。'Back' in item如果Back在字符串中,则返回True,否则返回False。净效果是我们用真和假替换最后一个词,然后根据这个键排序。你知道吗

相关问题 更多 >