Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

python - Remove partially duplicate tuples from list of tuples

I have a list of tuples and need to delete tuples if its 1st item is matching with 1st item of other tuples in the list. 3rd item may or may not be the same, so I cannot use set (I have seen this question - Grab unique tuples in python list, irrespective of order and this is not same as my issue)

For eg if I got a as:

[(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), 
 (0, 13, 'order1'), (28, 41, 'order3')]

I want the output as:

[(14, 27, 'order2'), (0, 13, 'order1'), (28, 41, 'order3')]

I am getting the desired output using below code.

for e, i in enumerate(a):
    r = [True if i[0] == k[0] and e != j else False for j, k in enumerate(a)]
    if any(r):
        a.pop(e)
pprint(a)

Is there a better or more pythonic way to achieve the same?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The usual way is keying a dict off whatever you want to dedupe by, for example:

>>> a = [(0, 13, 'order1'), (14, 27, 'order2'), (14, 27, 'order2.1'), (0, 13, 'order1'), (28, 41, 'order3')] 
>>> print(*{tup[:2]: tup for tup in a}.values()) 
(0, 13, 'order1') (14, 27, 'order2.1') (28, 41, 'order3')

This is O(n) time complexity, superior to O(n log n) groupby based approaches.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...