首页 > 解决方案 > 按嵌套索引对两个不同长度的列表进行排序

问题描述

我的问题与这个问题非常相似: Rearranging list based on order of another list

我有两个列表,列表中有元组,我希望它们按元组中的第一个元素排序 * 即使长度不相等或项目不同。

_list1 = [
 ('CLINIQUE Lash', 'https://ww', '$25.00', 'Lash Power'),
 ('LEONIDAS Premium Chocolate 245GR', 'https://default/_240__1.jpg', '$28.90', 'LEONIDAS'), 
 ('Twix Chocolate 6x50 Gr', 'http', '$5.00', 'TWIX'),
 ('Montale Chocolate Greedy Edp 100ml', 'https:jpg', '$105.00', 'Chocolate Greedy'),
 ('Valrhona Equinoxe Almods & Hazelnuts Dark Chocolate Gift Box 125 Gr', '_47170.jpg', '$14.90', 'VALRHONA') ]

_list2 = [
 ('Twix Chocolate 6x50 Gr', 'ht9/1944__1944.jpg', '$5.00', 'TWIX'),
 ('something else', '44127__44129.jpg', '$25.00', 'Lash Power'),
 ('LEONIDAS Premium Chocolate 245GR', 'h_240__1.jpg', '$28.90', 'LEONIDAS'),
 ('Montale Chocolate Greedy Edp 100ml', 'http/36344__36346.jpg', '$105.00', 'Chocolate Greedy') ]

预期输出:

_list1 = [
 ('CLINIQUE Lash', 'https://ww', '$25.00', 'Lash Power'),
 ('LEONIDAS Premium Chocolate 245GR', 'https://default/_240__1.jpg', '$28.90', 'LEONIDAS'), 
 ('Twix Chocolate 6x50 Gr', 'http', '$5.00', 'TWIX'),
 ('Montale Chocolate Greedy Edp 100ml', 'https:jpg', '$105.00', 'Chocolate Greedy'),
 ('Valrhona Equinoxe Almods & Hazelnuts Dark Chocolate Gift Box 125 Gr', '_47170.jpg', '$14.90', 'VALRHONA') ]

_list2 = [
 ('LEONIDAS Premium Chocolate 245GR', 'h_240__1.jpg', '$28.90', 'LEONIDAS'),
 ('Twix Chocolate 6x50 Gr', 'ht9/1944__1944.jpg', '$5.00', 'TWIX'),
 ('Montale Chocolate Greedy Edp 100ml', 'http/36344__36346.jpg', '$105.00', 'Chocolate Greedy'),
 ('something else', '44127__44129.jpg', '$25.00', 'Lash Power')]

标签: pythonlist

解决方案


您可以使用 adict来存储元组中的索引和第一个元素,_list1并以此为基础对内联进行排序_lsit2

item_idx = {t[0]: i for i, t in enumerate(_list1)}
# make sure to send to the end of the list the items that are not in list 1 tuples first position
max_value = len(_list1)
_list2.sort(key=lambda t: item_idx.get(t[0], max_value))

如果您打印_list2/输出:

[('LEONIDAS Premium Chocolate 245GR', 'h_240__1.jpg', '$28.90', 'LEONIDAS'),
 ('Twix Chocolate 6x50 Gr', 'ht9/1944__1944.jpg', '$5.00', 'TWIX'),
 ('Montale Chocolate Greedy Edp 100ml',
  'http/36344__36346.jpg',
  '$105.00',
  'Chocolate Greedy'),
 ('something else', '44127__44129.jpg', '$25.00', 'Lash Power')]

推荐阅读