假设我在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')
]发布于 2017-01-10 22:41:01
您可以简单地使用列表理解,并检查每个匹配元组中的第一个元素的计数是否与元组的长度相同:
>>> r = [i for i in myList if i.count(i[0]) != len(i)]
>>> r
[('a', 'b', 'c'), ('d', 'e', 'f')]发布于 2017-01-10 22:43:41
您可以使用http://treyhunner.com/2015/12/python-list-comprehensions-now-in-color/并使用内置的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')]
>>> 发布于 2017-01-10 22:41:00
将每个元组转换为一个集合;如果结果长度为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')]https://stackoverflow.com/questions/41579691
复制相似问题