擅长:python、mysql、java
<p>我就是这么做的:</p>
<pre><code>def non_unique(data):
temp = [sub[0] for sub in [(item, data.count(item)) for item in set(data)] if sub[1] > 1]
return [i for i in data if i in temp]
</code></pre>
<hr/>
<p>说明:</p>
<p><code>[(item, data.count(item)) for item in set(data)]</code>:
将数据转换为一个集合,以获取唯一的值并计算每个值的出现次数。它返回一个元组,在<em>索引-1</em>位置包含计数。你知道吗</p>
<p><code>[sub[0] for sub in [..] if sub[1] > 1]</code>:
对于计数大于1的所有项,从内部列表中包含的元组中获取项<em>索引-0</em>。你知道吗</p>
<p><code>[i for i in data if i in temp]</code>:
最后,要保持原始列表的顺序,请遍历它并保留以前提取的所有内容。你知道吗</p>
<hr/>
<p>注意</p>
<p>此解决方案比简单地执行<code>[d for d in data if data.count(d) > 1]</code>更有效,因为此变体多次获得每个重复的<code>count</code>。你知道吗</p>
<hr/>
<p>断言:</p>
<pre><code>assert isinstance(non_unique([1]), list), "The result must be a list"
assert non_unique([1, 2, 3, 1, 3]) == [1, 3, 1, 3], "1st example"
assert non_unique([1, 2, 3, 4, 5]) == [], "2nd example"
assert non_unique([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5], "3rd example"
assert non_unique([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9], "4th example"
</code></pre>
<p>它们都不升高<code>AssertionError</code></p>