PDA

View Full Version : compare similar items nested in a list, and removing them


dimitarsp
06-08-2012, 02:28 AM
I am trying to find duplicates in relationship and omit them from my list. I have tried nested if statements, but I haven't gotten the right solution yet.

list = [[u'polySurface5.e[4]', u'polySurface5.e[1]', .5], [u'polySurface5.e[8]', u'polySurface5.e[2]', .9], [u'polySurface5.e[1]', u'polySurface5.e[4]', .5], [u'polySurface5.e[2]', u'polySurface5.e[9]', 1.2], [u'polySurface5.e[2]', u'polySurface5.e[2]', 0] ]
in the following list, I want to remove "doubles", and values where that last item is 0. I want to end up with something like this:

newlist = [[u'polySurface5.e[4]', u'polySurface5.e[1]', .5], [u'polySurface5.e[8]', u'polySurface5.e[2]', .9], [u'polySurface5.e[2]', u'polySurface5.e[9]', 1.2] ]

in which way can i compare [u'polySurface5.e[4]', u'polySurface5.e[1]', .5] with [u'polySurface5.e[1]', u'polySurface5.e[4]', .5] and remove any occurrence after the first one?

many thanks!

EightBit
06-08-2012, 05:23 AM
I haven't tried this with a list of lists, but give it a go (beware forum indenting):
def removeDups(list):
# Remove Duplicates from list using a dictionary
list = dict.fromkeys(list)
list = list.keys()
return list

gtbull80
06-08-2012, 05:59 AM
I was thinking along the same lines as EightBit. And I tried:


myList = [2, 2, 4, 4, 2, 6, 4, 8, 8]
myNewList = list(set(myList))




Neither of our approaches appear to work with nested lists. A longer, more convoluted way to do it might be to use the cmp() function.

cmp([u'polySurface5.e[8]', u'polySurface5.e[2]', .9], [u'polySurface5.e[8]', u'polySurface5.e[2]', .9]) #returns 0...this is a duplicate

cmp([u'polySurface5.e[4]', u'polySurface5.e[1]', .5], [u'polySurface5.e[8]', u'polySurface5.e[2]', .9]) #returns -1...the first item is "less"

cmp([u'polySurface5.e[9]', u'polySurface5.e[1]', .5], [u'polySurface5.e[8]', u'polySurface5.e[2]', .9]) #returns 1...the first item is "greater"

Then you can iterate through your list and compare [0] to [1] then [0] to [2] then [0] to [3]...then delete by index. Then start again from [1] to [2] then [1] to [3]...deleting common...then [2] to [3] then [2] to [4]...etc.

Use the following example to delete by index:


aaa = range(0,10)
del aaa[2]

NaughtyNathan
06-08-2012, 09:54 AM
I was wondering, where does list actually come from? Do you generate list in your own code? if so rather than create and populate it, and then try to "fix" it, why don't you change how this list is stored? If you changed it into a dictionary and used the last value as the key, you would have the end result that you wanted straight away...

CGTalk Moderation
06-08-2012, 09:54 AM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.