Jst*_*uff 7 python sorting list
更新:列表中填充了我编辑列表的字符串以显示此信息
我有3个不同的列表,如
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')]
Run Code Online (Sandbox Code Playgroud)
我想把它们结合起来如
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')]
Run Code Online (Sandbox Code Playgroud)
或者任何其他形式允许我按照标题为部分的列表中的数字对它们进行排序.
在这种情况下,它会
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')
Run Code Online (Sandbox Code Playgroud)
我需要这样,所以我最终可以按部分将排序列表导出到excel中.如果您能想出更好的显示/格式化方式,请分享!
尝试这个,
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')]
Run Code Online (Sandbox Code Playgroud)