我尝试使用set()
python方法来查找列表中的唯一元素。它可以很好地移除所有重复项。但这里是我的要求,我想要通过使用set()
方法来获取要删除的元素。任何人都可以帮助我吗?如何识别在python中从set()中移除的元素?
a=[1,2,3,1,4]
b=set(a)
Output:[1,2,3,4]
我的预期输出是从set()
方法
我尝试使用set()
python方法来查找列表中的唯一元素。它可以很好地移除所有重复项。但这里是我的要求,我想要通过使用set()
方法来获取要删除的元素。任何人都可以帮助我吗?如何识别在python中从set()中移除的元素?
a=[1,2,3,1,4]
b=set(a)
Output:[1,2,3,4]
我的预期输出是从set()
方法
你可以扩展集类(有自己的一套类说MYSET)和重写此功能
def _update(self, iterable):
# The main loop for update() and the subclass __init__() methods.
data = self._data
# Use the fast update() method when a dictionary is available.
if isinstance(iterable, BaseSet):
data.update(iterable._data)
return
value = True
if type(iterable) in (list, tuple, xrange):
# Optimized: we know that __iter__() and next() can't
# raise TypeError, so we can move 'try:' out of the loop.
it = iter(iterable)
while True:
try:
for element in it:
data[element] = value
return
except TypeError:
transform = getattr(element, "__as_immutable__", None)
if transform is None:
raise # re-raise the TypeError exception we caught
data[transform()] = value
else:
# Safe: only catch TypeError where intended
for element in iterable:
try:
data[element] = value
except TypeError:
transform = getattr(element, "__as_immutable__", None)
if transform is None:
raise # re-raise the TypeError exception we caught
data[transform()] = value
的项目,所以你的答案基本上是“改变这些35行代码中的东西”?... – shx2 2015-04-01 10:29:38
是的,因为这就是问题所在。对于那些已经使用Counter的人,我相信你已经给出了一个替代方案,而不是回答所问的问题(带有额外的循环等)感谢投票顺便说一句:) – 2015-04-01 10:37:48
collections.Counter
除去[1]
.The元件是有用这里。
from collections import Counter
counts = Counter(a)
b = set(counts.keys())
for x, count in counts.items():
if count > 1:
print('%d appearances of %s were removed in the set' % (count-1, x))
你甚至不需要设置。你需要对每个元素进行一次以上的计数。来自藏书的反驳与字典理解应该会让你在那里。
from collections import Counter
a = [1, 1, 1, 2, 2, 3, 4]
removed = {k: v-1 for k, v in Counter(a).iteritems() if v > 1}
>>> removed
Out[8]: {1: 2, 2: 1}
这将返回一个仅包含项目的一组从原来的集合中删除:
>>> a = [1, 2, 3, 4, 1, 1, 5]
>>> set(i for i in a if a.count(i) > 1)
>>> {1}
我认为你是以稍微混合的方式接近问题。而不是试图让set()
做一些不打算做的事情(返回重复列表),我会用collections.Counter()
来收集重复,然后从中获取重复。
下面是一些代码:
#!python
from collections import Counter
c = Counter([1,2,3,1,4])
dupes = [k for k,v in c.items() if v>1]
b = set(c.keys())
与Counter
from collections import Counter
a = [1, 2, 3, 1, 4]
>>>[i for i in Counter(a) if Counter(a)[i] > 1]
[1]
如果什么输入'[1,2,3,1,4,1,1]'试试这个? – thefourtheye 2015-03-25 07:06:29
得到他们的计数,并检查计数> 1. – 2015-03-25 07:07:28