如果nTuples中的每个元素都相同,如何从列表中删除nTuples?

2024-04-25 03:45:41 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我想删除n元组中每个元素都相同的任何n元组。在上面的例子中,我想删除元组('a','a','a')('b','b','b'),因为这些元组中的每个元素都是相同的。你知道吗

我编写了一个嵌套for循环来实现这一点,但这样做似乎效率很低/不太像python。关于如何更简单有效地完成这项工作有什么想法吗?你知道吗

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

Tags: ofthetoinforsizeifcount
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')]

可以使用list comprehension并使用内置的^{}函数测试给定元组中的所有元素是否相等。你知道吗

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

您只需使用列表理解并检查每个匹配元组中第一个元素的计数是否与元组的长度相同:

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

相关问题 更多 >