组合元组的2D列表,然后用Python对其进行排序 [英] Combing 2D list of tuples and then sorting them in Python

查看:80
本文介绍了组合元组的2D列表,然后用Python对其进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:列表中填充了我编辑过的字符串以显示此字符串

Update: The list are filled with strings I edited the list to show this

我有3个不同的列表,例如

I have 3 different list such as

Section = [('1', '1.1', '1.2'), ('1', '2', '2.2', '3'), ('1', '1.2', '3.2', '3.5')] 
Page = [('1', '1', '3'), ('1', '2', '2', '2'), ('1', '2', '3', '5')]
Titles = [('General', 'Info', 'Titles'), ('More', 'Info', 'Section', 'Here'), ('Another', 'List', 'Of', 'Strings')]

我想将它们合并在一起,例如

I want to combine them such as

Combined_List = [('1', '1.1', '1.2'), ('1', '2', '2.2', '3'), ('1', '1.2', '3.2', '3.5'),
                 ('1', '1', '3'), ('1', '2', '2', '2'), ('1', '2', '3', '5'),  
                 ('General', 'Info', 'Titles'), ('More', 'Info', 'Section', 'Here'), ('Another', 'List', 'Of', 'Strings')]

或其他任何允许我按照标题部分中的数字对它们进行排序的形式.

Or any other form that allows me to then sort them by the numbers in the list titled sections.

在这种情况下应该是

  Sorted_list = [('1', '1', '1', '1.1', '1.2', '1.2', '2', '2.2', '3', '3.2', '3.5'), 
                 ('1', '1', '1', '1', '3', '2', '2', '2', '2', '3', '5'),
                 ('General', 'More', 'Another', 'Info', 'Titles', 'List', 'Info', 'Section', 'Here', 'Of', 'Strings')

我需要这样,以便最终可以将按科目排序的列表导出到excel.如果您想出更好的显示/格式设置方法,请务必分享!

I need it like this so I can eventually export a sorted list by Section into excel. If you can think of a better way to display/format please do share!

推荐答案

尝试一下,

Section = [('1', '1.1', '1.2'), ('1', '2', '2.2', '3'), ('1', '1.2', '3.2', '3.5')] 
Page = [('1', '1', '3'), ('1', '2', '2', '2'), ('1', '2', '3', '5')]
Titles = [('General', 'Info', 'Titles'), ('More', 'Info', 'Section', 'Here'), ('Another', 'List', 'Of', 'Strings')]

# Flat a list of tuples into a list
l1 = [item for sublist in Section for item in sublist]
l2 = [item for sublist in Page for item in sublist]
l3 = [item for sublist in Titles for item in sublist]

# Python2, `zip` returns a list of tuples
#result = zip(*sorted(zip(l1, l2, l3), key=lambda x:float(x[0])))

# Python3, `zip` returns an iterator of tuples
result = list(zip(*sorted(zip(l1, l2, l3), key=lambda x:float(x[0]))))

print(result)
# Output
[   ('1', '1', '1', '1.1', '1.2', '1.2', '2', '2.2', '3', '3.2', '3.5'), 
    ('1', '1', '1', '1', '3', '2', '2', '2', '2', '3', '5'), 
    ('General', 'More', 'Another', 'Info', 'Titles', 'List', 'Info', 'Section', 'Here', 'Of', 'Strings')]

这篇关于组合元组的2D列表,然后用Python对其进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆