# Sorting by item_in_another_list

Paul McGuire ptmcg at austin.rr._bogus_.com
Wed Oct 25 14:38:41 EDT 2006

```"Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message
> "J. Clifford Dyer" <jcd at sdf.lonestar.org> wrote in message
> news:eho2kq\$lqc\$1 at aioe.server.aioe.org...
>> ZeD wrote:
>>> Paul Rubin wrote:
>>>
>>>>> A = [0,1,2,3,4,5,6,7,8,9,10]
>>>>> B = [2,3,7,8]
>>>>>
>>>>> desired_result = [2,3,7,8,0,1,4,5,6,9,10]
>>>>
>>>>   desired_result = B + sorted(x for x in A if x not in B)
>>>
>>> this. is. cool.
>>>
>>
>> Cool, yes, but I'm not entirely sure it does what the OP wanted.  Partly
>> because I'm not entirely sure what the OP wanted.  Counter example:
>>
>> Given these variables:
>>
>> A = [0,1,2,3,4,5,6,8,9,10]  # Note 7 is missing
>> B = [2,3,7,8]
>>
>> which of the following should the function yield?
>>
>
> From the original post:
>
> "I have two lists, A and B, such that B is a subset of A."
>
> So this is not a case that needs to be supported.
>
> did a random sampling from the list, and wanted to move the sampled items
> to the front of the list.
>
> -- Paul
>

Here is a little subclass of list that has some set-ish operators added.

-- Paul

# ListWithMath does set-like operations on lists, keeping list order
# stable where applicable
class ListWithMath(list):
def isSuperset(self,other):
return len(self ^ other) == len(other)

self.extend(other)
return self

def __isub__(self,other):
if self.isSuperset(other):
for i in other:
self.remove(i)
return self
else:
raise ValueError

def __ixor__(self,other):
for a in self[::-1]:
if not a in other:
self.remove(a)
return self

temp = ListWithMath(self)
temp += other
return temp

def __sub__(self,other):
temp = ListWithMath(self)
temp -= other
return temp

def __xor__(self,other):
temp = ListWithMath(self)
temp ^= other
return temp

return ListWithMath(other) + self
def __rsub__(self,other):
return ListWithMath(other) - self
def __rxor__(self,other):
return ListWithMath(other) ^ self

A = ListWithMath( [0,1,2,3,4,5,6,7,8,9,10] )
B = ListWithMath( [2,3,7,10,8] )

print "%s+(%s-%s)" % (B,A,B)
C = B+(A-B) # union and exclusion
print C

D = ListWithMath( [1,2,3,6,8,11] )
print "%s ^ %s" % (B,D)
print B^D # intersection

print "%s ^= %s" % (B,D)
B ^= D # in-place intersection
print B

print C
C += []
print C
C -= []
print C
C ^= []
print C

Prints:
[2, 3, 7, 10, 8]+([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]-[2, 3, 7, 10, 8])
[2, 3, 7, 10, 8, 0, 1, 4, 5, 6, 9]
[2, 3, 7, 10, 8] ^ [1, 2, 3, 6, 8, 11]
[2, 3, 8]
[2, 3, 7, 10, 8] ^= [1, 2, 3, 6, 8, 11]
[2, 3, 8]
[2, 3, 7, 10, 8, 0, 1, 4, 5, 6, 9]
[2, 3, 7, 10, 8, 0, 1, 4, 5, 6, 9]
[2, 3, 7, 10, 8, 0, 1, 4, 5, 6, 9]
[]

```