【问题标题】:How to return a list containing common elements with no duplicates如何返回包含没有重复的常见元素的列表
【发布时间】:2011-05-18 01:42:32
【问题描述】:
def common_elements(list1, list2):
    """
    Return a list containing the elements which are in both list1 and list2

    >>> common_elements([1,2,3,4,5,6], [3,5,7,9])
    [3, 5]
    >>> common_elements(["this","this","n","that"],["this","not","that","that"])
    ['this', 'that']
    """

    result = []
    for element in list1:
        if element in list2:
            result.append(element)
    return result

到目前为止我有这个,但它返回重复,例如:

common_elements(["this","this","n","that"],["this","not","that","that"])

返回为:['this', 'this', 'that']

【问题讨论】:

    标签: python


    【解决方案1】:

    使用set.intersection(),因为这意味着不需要将list2转换为集合

    def common_elements(list1, list2):
        return set(list1).intersection(list2)
    

    选择较短的列表转换为集合更有效

    def common_elements(list1, list2):
        short_list, long_list = sorted((list1, list2), key=len)
        return set(short_list).intersection(long_list)
    

    当然要返回一个列表,你会使用

        return list(set(...))
    

    【讨论】:

      【解决方案2】:

      使用sets:

      >>> a, b = [1,2,3,4,5,6], [3,5,7,9]
      >>> set(a).intersection(b)
      set([3, 5])
      

      【讨论】:

      • set.intersection() 适用于任何可迭代对象,因此无需将 b 转换为 set
      • @gnibbler:谢谢,不记得了。更新了我的答案,并为你的答案投票。
      【解决方案3】:
      def common_elements(a, b):
          return list(set(a) & set(b))
      

      在这种情况下,我们取两个集合的交集,而这两个集合又是由两个列表构成的。每个集合由每个列表中的唯一项目组成。我们最终转换回列表,因为这是所需的返回类型。

      【讨论】:

        【解决方案4】:
        >>> a = [1,2,3,4,5,6]
        >>> b = [3,5,7,9]
        >>> list(set(a).intersection(b))
        [3, 5]
        

        编辑:不需要将 b 转换为集合。谢谢@Johnsyweb

        【讨论】:

        • set.intersection() 适用于 any 可迭代,因此无需将b 转换为setgnibbler's answer 更好。
        【解决方案5】:

        您想使用集合,因为它们有一些非常好的操作:

        >>> a = set([1, 2, 3, 4])
        >>> b = set([3, 4, 5, 6])
        >>> a.intersection(b)
        set([3, 4])
        >>> a.difference(b)
        set([1, 2])
        >>> b.intersection(a)
        set([5, 6])
        >>> a.union(b)
        set([1, 2, 3, 4, 5, 6])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-10-08
          • 1970-01-01
          • 1970-01-01
          • 2014-06-17
          • 1970-01-01
          • 1970-01-01
          • 2021-09-21
          • 2022-10-14
          相关资源
          最近更新 更多