[英]How to sort a list of list based on the same set value in the list?
a = [['a', 'b'], ['b'], ['b', 'a']]
因為第一個和第三個元素是相同的,如果將它們轉換為集合,我想對列表 'a' 進行排序,以便具有相同集合值的任何兩個元素彼此相鄰。 對於上面的示例,排序結果將是:
a = [['a', 'b'], ['b', 'a'], ['b']]
要么
a = [['b'], ['a', 'b'], ['b', 'a']]
您可以使用list(set(x))
作為您的密鑰。 由於這強加的排序有點隨意,您可以將sorted
添加到組合中:
a = [['a', 'b'], ['b'], ['b', 'a']]
a.sort(key=lambda x: sorted(set(x)))
請注意,這與使用key=sorted
因為重復元素的處理方式不同。
使用帶有frozenset
hash
一種方法:
sorted(a, key=lambda x: hash(frozenset(x)))
輸出:
[['b'], ['a', 'b'], ['b', 'a']]
使用更多元素進行測試:
a = [['a', 'b', 'c'], ['a', 'b'],
['b'], ['b', 'd'], ['b', 'a'],
['a', 'c'], ['b', 'c', 'a']]
sorted(a, key=lambda x: hash(frozenset(x)))
輸出:
[['a', 'c'],
['a', 'b', 'c'],
['b', 'c', 'a'],
['b'],
['b', 'd'],
['a', 'b'],
['b', 'a']]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.