python - 按嵌套索引对两个不同长度的列表进行排序
问题描述
我的问题与这个问题非常相似: 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')]
解决方案
您可以使用 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')]
推荐阅读
- python - 如何在 ../src/x86/ffi64.c:158 处修复 Python 函数“classify_argument”中的段错误
- metpy - 绘制 MetPy Q 向量
- python - 如何通过关键事件运行代码但不停止其他正在运行的功能
- php - 基于用户的 Dingo Api 节流
- python - 有没有办法从代码中查看 Python API 文档?
- reactjs - 在 ReactJs 中添加条带元素多个可发布键
- javascript - 如何使用 JQuery 为数组的每个值生成 HTML 元素?
- python - 着色 QPolygonItem
- excel - 从一个工作簿复制数据并粘贴到另一个工作簿中的下一个空行
- r - 如何给 spacyr 喂食?