【问题标题】:How to Remove n-Tuples From List Where Each Element within the n-Tuples is Identical?如何从列表中删除 n-Tuples,其中 n-Tuples 中的每个元素都相同?
【发布时间】:2017-05-25 14:00:32
【问题描述】:

假设我有一个 Python 中的 n 元组列表,就像这样(在示例中使用三元组,但希望它适用于任何元组大小):

myList = [('a','b','c'),
          ('a','a','a'),
          ('b','b','b'),
          ('d','e','f')
     ]

我想删除所有 n 元组的每个元素都相同的 n 元组。在上面的示例中,我想删除元组 ('a','a','a')('b','b','b'),因为这些元组中的每个元素都是相同的。

我编写了一个嵌套的 for 循环来执行此操作,但这样做似乎效率很低/不是很 Pythonic。有关如何更简单有效地做到这一点的任何想法?

def tuple_removal(aList):
    elements = len(aList) # number of elements in the list
    tuple_size = len(aList[0]) # size of the tuple
    for i in reversed(range(elements)):
        same_element_count = 1 # initialize counter to 1
        for j in range(tuple_size-1):
            # add one to counter if the jth element is equal to the j+1 element
            same_element_count += aList[i][j] == aList[i][j+1]
        if same_element_count == tuple_size:
            # remove the tuple at the ith index if the count of elements that are the same
            # is equal to the size of the tuple
            del aList[i]
    return(aList)

myNewList = tuple_removal(myList)
myNewList

# Output
myNewList = [('a','b','c'),
          ('d','e','f')
     ]

【问题讨论】:

    标签: python list python-3.x duplicates tuples


    【解决方案1】:

    您可以简单地使用 list comprehension 并检查每个匹配元组中第一个元素的计数是否与元组的长度不同:

    >>> r = [i for i in myList if i.count(i[0]) != len(i)]
    >>> r
    [('a', 'b', 'c'), ('d', 'e', 'f')]
    

    【讨论】:

    • 我已经在这里测试了所有答案,我相信你的答案是最快的 ;-) +1
    • 谢谢!我会接受@leaf 的关于速度的话。 13 行代码减少到 1 行。这很棒。 (也感谢所有其他答案)。
    【解决方案2】:

    您可以使用list comprehension 并使用内置的all() 函数测试给定元组中的所有元素是否相等。

    >>> myList = [('a','b','c'),
              ('a','a','a'),
              ('b','b','b'),
              ('d','e','f')
         ]
    >>> 
    >>> [el for el in myList if not all(x == el[0] for x in el)]
    [('a', 'b', 'c'), ('d', 'e', 'f')]
    >>> 
    

    【讨论】:

      【解决方案3】:

      将每个元组转换为一个集合;如果结果的长度为 1,则所有元素都相同。在列表推导中使用它作为过滤器,保留所有具有多个唯一元素的元组:

      def tuple_removal(lst):
          return [t for t in lst if len(set(t)) > 1]
      

      演示:

      >>> myList = [('a','b','c'),
      ...           ('a','a','a'),
      ...           ('b','b','b'),
      ...           ('d','e','f')
      ...      ]
      >>> tuple_removal(myList)
      [('a', 'b', 'c'), ('d', 'e', 'f')]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-20
        • 1970-01-01
        • 1970-01-01
        • 2022-07-24
        • 2018-03-11
        • 1970-01-01
        相关资源
        最近更新 更多