python - 组合元组的二维列表,然后在 Python 中对它们进行排序

标签 python list sorting

更新:列表中充满了字符串我编辑了列表以显示这一点

我有 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/

相关文章:

python - 如何连接两个 ID 不匹配的数据帧并创建新列来表示数据帧 ID 的来源?

python - pandas matplotlib .plot(kind ='hist') vs .plot(kind ='bar') 问题

R:将列表组件的值连接到另一个定义哪些组件在一起的列表

sorting - 如何通过float64值对map [string] float64排序?

python - XPath 返回空列表(命名空间问题?)

python - 漂亮的 Python 打印机?

wpf - 如何右对齐 DataTemplate 中的内容?

python - 检查字符串是否包含列表中的任何单词的最快方法

java - 使用比较器对链表进行排序

Javascript/jQuery - 重新排序 div