我有一个列表的列表如下:-
set_res = [{'88194e6889', '88194e688b', '88194e68d5'},
{'88194e6f45', '88194e6f4d'},
{'88194e6ab3', '88194e6abb'},
{'88194e6a8b',
'88194e6ac3',
'88194e6acb',
'88194e6ad5',
'88194e6add'},
{'88194e61a1',
'88194e61a3',
'88194e61a7',
'88194e61ab',
'88194e61bd',
'88194e6f49'}]
当我试图将它们合并成一个时,它不会以正确的顺序合并,我尝试过set.union(),reduce(),iterloops来合并所有返回的东西以不同的顺序。方法1:-
from functools import reduce
reduce(set.union,set_res[0:5])
结果:
{'88194e61a1',
'88194e61a3',
'88194e61a7',
'88194e61ab',
'88194e61bd',
'88194e6889',
'88194e688b',
'88194e68d5',
'88194e6a8b',
'88194e6ab3',
'88194e6abb',
'88194e6ac3',
'88194e6acb',
'88194e6ad5',
'88194e6add',
'88194e6f45',
'88194e6f49',
'88194e6f4d'}
方法2:-
set.union(*set_res[0:5])
结果:
{'88194e61a1',
'88194e61a3',
'88194e61a7',
'88194e61ab',
'88194e61bd',
'88194e6889',
'88194e688b',
'88194e68d5',
'88194e6a8b',
'88194e6ab3',
'88194e6abb',
'88194e6ac3',
'88194e6acb',
'88194e6ad5',
'88194e6add',
'88194e6f45',
'88194e6f49',
'88194e6f4d'}
异常输出的顺序:-
['88194e6889', '88194e688b', '88194e68d5',
'88194e6f45', '88194e6f4d',
'88194e6ab3', '88194e6abb',
'88194e6a8b',
'88194e6ac3',
'88194e6acb',
'88194e6ad5',
'88194e6add',
'88194e61a1',
'88194e61a3',
'88194e61a7',
'88194e61ab',
'88194e61bd',
'88194e6f49']
有什么最好的方法可以将一个集合以有序的形式组合成一个?
集合是无序的,所以你不能控制元素的顺序。
你所能达到的最好的输入是基于列表保持部分顺序:
from itertools import chain
out = list(dict.fromkeys(chain.from_iterable(set_res)))
输出:
['88194e68d5', '88194e6889', '88194e688b', '88194e6f45', '88194e6f4d', '88194e6ab3', '88194e6abb', '88194e6ac3', '88194e6add', '88194e6ad5', '88194e6acb', '88194e6a8b', '88194e61a7', '88194e61bd', '88194e61ab', '88194e61a1', '88194e6f49', '88194e61a3']
更好的例子:
set_res = [{'B', 'A', 'C'},
{'A', 'D'},
{'B', 'F', 'E', 'A', 'C'}]
输出(分隔显示元素的来源):
['C', 'A', 'B', # we can't control the order here
'D', # A was removed
'E', 'F' # A/B/C were removed, we can't control the order of E/F
]