更新:列表中充满了字符串我编辑了列表以显示这一点
我有 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')]
我想把它们结合起来,比如
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')]
或任何其他允许我按标题部分列表中的数字对它们进行排序的形式。
在这种情况下会是
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 中。如果您能想到更好的显示/格式方式,请分享!
最佳答案
试试这个,
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')]
关于python - 组合元组的二维列表,然后在 Python 中对它们进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37592787/