python - 如何从 n 元组中每个元素相同的列表中删除 n 元组?

标签 python list python-3.x duplicates tuples

假设我有一个 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')
     ]

最佳答案

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

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

关于python - 如何从 n 元组中每个元素相同的列表中删除 n 元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41579691/

相关文章:

python-3.x - 无法使用带有标记为索引的字符串的 loc 进行设置

python - 如何将 web URL.text 数据转换为 Dataframe

python - QTableWidget 动态行 w/QComboBox

python - 通过 GCS 触发器在云功能中获取用户信息

python - 如何在 GAE 上定期运行 Python 函数

python - 如何检查类是否为异常类?

python - 尝试在 Python 2.7 中导入任何模块时,如何解决 "NameError: name ' null' 未定义”错误

python - 嵌套列表代码中缺少第一个列表

c# - 如何遍历字典列表?

Python 好奇心 : [] > lambda n: n