【问题标题】:How to Identify the elements which are removed from set() in python?如何识别从 python 中的 set() 中删除的元素?
【发布时间】:2015-05-28 18:09:02
【问题描述】:

我尝试使用 python 的set() 方法来查找列表中的唯一元素。它可以很好地删除所有重复项。但这是我的要求,我想获取使用set() 方法删除的元素。有人可以帮我吗?

a=[1,2,3,1,4]
b=set(a)
Output:[1,2,3,4]

我的预期输出是[1]。从set() 方法中删除的元素

【问题讨论】:

  • 如果输入的是[1,2,3,1,4, 1, 1]怎么办?
  • 获取他们的计数并检查计数> 1的项目。

标签: python python-2.7 csv python-3.x set


【解决方案1】:

简单的python示例,

def finder(s):
    seen,yields=set(),set()
    for i in s:
      if i in seen and i not in yields:
          yield i
          yields.add(i)
      else:
          seen.add(i)
    print(type(seen), seen )
    
a = [1,2,3,1,4] 
print(list(finder(a)))

生产,

<class 'set'> {1, 2, 3, 4}
[1]

[Program finished] 

【讨论】:

    【解决方案2】:

    这将返回一个仅包含从原始集合中删除的项目的集合:

    >>> a = [1, 2, 3, 4, 1, 1, 5]
    
    >>> set(i for i in a if a.count(i) > 1)
    
    >>> {1}
    

    【讨论】:

      【解决方案3】:

      Counter试试这个

      from collections import Counter
      a = [1, 2, 3, 1, 4]
      >>>[i for i in Counter(a) if Counter(a)[i] > 1]
      [1]
      

      【讨论】:

        【解决方案4】:

        我认为您正在以一种稍微混淆的方式处理问题。与其试图让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())
        

        【讨论】:

          【解决方案5】:

          你可以扩展 Set 类(有你自己的 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
          

          【讨论】:

          • 是的,因为这就是问题所在。对于那些使用 Counter 的人,我相信您已经给出了替代方案,而不是回答所询问的内容(带有额外的循环等)感谢您的反对票:)
          【解决方案6】:

          你甚至不需要设置。您希望计算每个元素多次出现的次数。集合中的计数器和字典理解应该可以帮助您实现目标。

          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}
          

          【讨论】:

            【解决方案7】:

            collections.Counter 在这里很有用。

            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))
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2018-04-27
              • 2014-01-04
              • 2011-02-21
              • 1970-01-01
              • 2019-10-28
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多