On 09/24/10 13:01, Ethan Furman wrote:
John Posner wrote:
Another "missing feature" candidate: sublist
>>> 'bc' in 'abcde'
True
>>> list('bc') in list('abcde')
False
I'm not aware of any idioms, but how about a simple function?
def listinlist(list1, list2):
"checks if list1 is in list2"
if not list1:
return True
if not list2:
return False
length = len(list1)
pos = 0
while True:
try:
pos = list2.index(list1[0], pos)
except ValueError:
return False
if list2[pos:pos+length] == list1:
return True
pos += 1
Which I suppose could be rewritten something like
def listinlist(l1, l2):
len1 = len(l1)
offsets_to_consider = 1 + len(l2) - len1
return any(
l1 == l2[i:i+len1]
for i in xrange(offsets_to_consider)
)
Foldable into a one-line version if one's sick enough to use it:
list_in_list = lambda l1, l2: any(l1 == l2[i:i+len(l1)] for i
in range(1 + len(l2) - len(l1)))
-tkc
--
http://mail.python.org/mailman/listinfo/python-list