Skip to content

Instantly share code, notes, and snippets.

@anandkunal
Created March 8, 2010 07:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anandkunal/324956 to your computer and use it in GitHub Desktop.
Save anandkunal/324956 to your computer and use it in GitHub Desktop.
Python List Predicates
from types import FunctionType
from UserList import UserList
class PredicateList(UserList):
def Exists(self, predicate):
"""Returns true if the predicate is satisfied by at least one list member."""
if type(predicate) is FunctionType:
for item in self.data:
if predicate(item):
return True
return False
else:
return predicate in self.data
def GetIndex(self, predicate, reversed):
"""Common functionality shared by FirstIndex and LastIndex."""
xr = xrange(len(self.data))
if reversed:
xr = xr.__reversed__()
for i in xr:
try:
if type(predicate) == FunctionType:
if predicate(self.data[i]):
return i
else:
if self.data[i] == predicate:
return i
# Function predicates that check object properties will fail on simple
# types like strings. This is rather unelegant, but works.
except AttributeError:
pass
return None
def FirstIndex(self, predicate):
"""Returns the first integer position in the list that satisfies the predicate."""
return self.GetIndex(predicate, False)
def FirstValue(self, predicate):
"""Returns the first value in the list that satisfies the predicate."""
firstObjectIndex = self.FirstIndex(predicate)
if not firstObjectIndex is None:
return self.data[firstObjectIndex]
else:
return None
def LastIndex(self, predicate):
"""Returns the last integer position in the list that satisfies the predicate."""
return self.GetIndex(predicate, True)
def LastValue(self, predicate):
"""Returns the last value in the list that satisfies the predicate."""
lastObjectIndex = self.LastIndex(predicate)
if not lastObjectIndex is None:
return self.data[lastObjectIndex]
else:
return None
class Person():
def __init__(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
def __str__(self):
return '%s %s' % (self.firstName, self.lastName)
sampleList = PredicateList()
sampleList.append('3')
sampleList.append('2')
sampleList.append('1')
sampleList.append(Person('Joe', 'Shmoe'))
sampleList.append('5')
sampleList.append('2')
print sampleList
# Existence checks
print sampleList.Exists('2')
print sampleList.Exists(lambda x: x == '2')
# First index checks
print sampleList.FirstIndex('2')
print sampleList.FirstIndex(lambda x: x == '2')
# First object checks
print sampleList.FirstValue('2')
print sampleList.FirstValue(lambda person: person.firstName == 'Joe')
# Last index checks
print sampleList.LastIndex('2')
print sampleList.LastIndex(lambda x: x == '2')
# Last object checks
print sampleList.LastValue('2')
print sampleList.LastValue(lambda person: person.lastName == 'Shmoe')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment