假设我有一个 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/