問題描述
我知道類似的問題已經(jīng)在 Stack Overflow 上被問過很多次了,但我需要從列表中刪除重復的元組,但不僅僅是它們的元素匹配,它們的元素必須按相同的順序排列.換句話說,(4,3,5)
和 (3,4,5)
都將出現(xiàn)在輸出中,而如果兩者都有 (3,3,5)
和 (3,3,5)
,只有一個會在輸出中.
I know questions similar to this have been asked many, many times on Stack Overflow, but I need to remove duplicate tuples from a list, but not just if their elements match up, their elements have to be in the same order. In other words, (4,3,5)
and (3,4,5)
would both be present in the output, while if there were both(3,3,5)
and (3,3,5)
, only one would be in the output.
具體來說,我的代碼是:
Specifically, my code is:
import itertools
x = [1,1,1,2,2,2,3,3,3,4,4,5]
y = []
for x in itertools.combinations(x,3):
y.append(x)
print(y)
其中的輸出很長.例如,在輸出中,應(yīng)該同時存在 (1,2,1)
和 (1,1,2)
.但是應(yīng)該只有一個(1,2,2)
.
of which the output is quite lengthy. For example, in the output, there should be both (1,2,1)
and (1,1,2)
. But there should only be one (1,2,2)
.
推薦答案
set
會解決這個問題:
set
will take care of that:
>>> a = [(1,2,2), (2,2,1), (1,2,2), (4,3,5), (3,3,5), (3,3,5), (3,4,5)]
>>> set(a)
set([(1, 2, 2), (2, 2, 1), (3, 4, 5), (3, 3, 5), (4, 3, 5)])
>>> list(set(a))
[(1, 2, 2), (2, 2, 1), (3, 4, 5), (3, 3, 5), (4, 3, 5)]
>>>
set
將僅刪除 exact 個重復項.
set
will remove only exact duplicates.
這篇關(guān)于如果它們完全相同,包括項目的順序,則從列表中刪除重復的元組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!