1

In a nested list (like the one below) that is continuous, I want to remove duplicate entry where first and third are equal values. What is the most efficient way of doing this?

 [[a, 1, a], [b, 1, b], [c, 2, d],[e, 4,g]

Return

 [[c, 2, d],[e, 4,g]]
1
  • Said more clearly you want to return all sublists which are not like [x, y, x]. Is that correct? Commented Apr 9, 2015 at 17:33

2 Answers 2

2
>>> seq = [['a', 1, 'a'], ['b', 1, 'b'], ['c', 2, 'd'],['e', 4, 'g']]
>>> seq = [item for item in seq if item[0] != item[2]]
>>> print seq
[['c', 2, 'd'], ['e', 4, 'g']]
Sign up to request clarification or add additional context in comments.

Comments

1

What you want to do is go through each sublist, and go through each item in that sublist. I there is a duplicate item in that sublist set the flag to True and ignore it, if not then append that list to a new list.

lists = [['a', 1, 'a'], ['b', 1, 'b'], ['c', 2, 'd'],['e', 4,'g']]
newLists = []
for l in lists:
    if l[0] != l[len(l) - 1]:
        newLists.append(l)

print newLists

1 Comment

This looks like it would incorrectly eliminate some values. For example, ['e', 'e','g'] would be removed even though its first item doesn't equal its third item.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.