<p>有一种方法:</p>
<pre><code>def bin_unique(partials, parents):
bins = []
for (ptx,par) in zip(partials, parents):
pair_assigned = False
# Try to find an existing bin that doesn't contain the parent.
for bin_contents in bins:
if par not in bin_contents:
bin_contents[par] = (ptx, par)
pair_assigned = True
break
# If we haven't been able to assign the pair, create a new bin
# (with the pair as it's first entry)
if not pair_assigned:
bins.append({par: (ptx, par)})
return bins
</code></pre>
<p><strong>用法</strong></p>
<pre><code>partials = [1,2,3,4,5,6,7,8,9,10]
parents = ['a','b','c','d','a','d','f','c','c','a']
binned = bin_unique(partials, parents)
</code></pre>
<p><strong>输出</strong></p>
<pre><code># Print the list of all dicts
print(binned)
# [
# {'a': (1, 'a'), 'b': (2, 'b'), 'c': (3, 'c'), 'd': (4, 'd'), 'f': (7, 'f')},
# {'a': (5, 'a'), 'd': (6, 'd'), 'c': (8, 'c')},
# {'c': (9, 'c'), 'a': (10, 'a')}
# ]
# You can access the bins via index
print(binned[0]) # {'a': (1, 'a'), 'b': (2, 'b'), 'c': (3, 'c'), 'd': (4, 'd'), 'f': (7, 'f')}
print(len(binned)) # 3
# Each bin is a dictionary, keyed by parent, but the values are the (partial, parent) pair
print(binned[0].keys()) # dict_keys(['a', 'b', 'c', 'd', 'f'])
print(binned[0].values()) # dict_values([(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (7, 'f')])
# To show that all the transactions exist
all_pairs = [pair for b in binned for pair in b.values()]
print(sorted(all_pairs) == sorted(zip(partials, parents))) # True
</code></pre>