【发布时间】:2017-05-25 14:00:32
【问题描述】:
假设我有一个 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')
]
【问题讨论】:
标签: python list python-3.x duplicates tuples