I have a large list
[[1,.., ..],[2,...,...],[5,...,...],[1,...,...]]
I need to remove all elements that have the same first value. (keep only once)
How to do it most efficiently?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Keep a
setof the first values seen so far, and only keep sublists if their first value isn’t in the set.Because
set.addalways returnsNone,keys.add(sublist[0]) or sublistis the same asNone or sublistwhich is the same assublist, so it doesn’t affect what gets kept in the list, while allowing you to add values to the set inside a list comprehension.