擅长:python、mysql、java
<p>跳过重复项的一个常见解决方案是保留一个包含您已经看到的所有元素的集合。如果以前见过对象,则不会将其添加到结果中。在</p>
<p>棘手的一点是,您尝试取消复制的对象是驻留在集合中不同元组中的多个对象的聚合。使用<code>groupby</code>是将这些对象集中在一个方便的包中的有效方法。在</p>
<pre><code>from itertools import groupby
input_tuple = (
(1, 'name1', 'Noah'),
(1, 'name2', 'Liam'),
(2, 'name3', 'Mason'),
(3, 'name4', 'Mason'),
(4, 'name5', 'Noah'),
(4, 'name6', 'Liam'),
(5, 'name7', 'Elijah'),
(5, 'name8', 'Noah'),
(5, 'name9', 'Liam')
)
seen = set()
result = []
for _, group in groupby(input_tuple, key=lambda t: t[0]):
#convert from iterator to list, since we want to iterate this more than once
group = list(group)
#extract just the names from each tuple.
names = tuple(t[2] for t in group)
#check for duplicates, but only for name groups with more than one element.
if len(names) == 1 or names not in seen:
result.extend(group)
seen.add(names)
print(result)
</code></pre>
<p>结果:</p>
^{pr2}$