假设我在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')
]
将每个元组转换为一个集合;如果结果的长度为1,则所有元素都相同。在列表理解中,将此用作筛选器,保留具有多个唯一元素的所有元组:
演示:
可以使用list comprehension并使用内置的^{} 函数测试给定元组中的所有元素是否相等。你知道吗
您只需使用列表理解并检查每个匹配元组中第一个元素的计数是否与元组的长度相同:
相关问题 更多 >
编程相关推荐