-2

I have about a list of lists and I want to check if an element in one list matches any other element. For example I have a list of lists:

lists = [['12','sam'],['13','dan'],['15','dan'],['12','john']]

My question is I want to loop through this list of lists to check whether the element in the second position e.g. 'sam' is the same as any other element in the second position. If there isn't a match, return the full list.

Example output:

lists = [['12', 'sam'], '12','john']]
martineau
  • 119,623
  • 25
  • 170
  • 301
theBean
  • 123
  • 10
  • 1
    Did you try to write something? Add the code – Dekel Dec 17 '16 at 19:22
  • 3
    It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on his own. A good way to show this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the [FAQ](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/help/how-to-ask). – Rory Daulton Dec 17 '16 at 19:22
  • 1
    Also, your problem description is not clear. Do you mean you want your returned list to have the sub-lists of the parameter list that have no duplicates in the second value and to exclude all copies of the duplicates? Are all the values of the sub-lists strings, or could there be a mutable value? – Rory Daulton Dec 17 '16 at 19:23

1 Answers1

0

extract the labels with

labels = [item[1] for item in lists]

then use for example the code in this answer to find the elements that are not duplicates:

import collections
unique_labels = []
for item, count in collections.Counter(labels).items():
    if count == 1:
        unique_labels.append(item)

and finally take only the elements of lists whose label is in labels:

output = [item for item in lists if item[1] in unique_labels]
Community
  • 1
  • 1
glS
  • 1,209
  • 6
  • 18
  • 45