reduce expression to test sublist
Jussi Piitulainen
jpiitula at ling.helsinki.fi
Sat Jan 5 21:41:24 CET 2013
Asim writes:
> Hi All
>
> The following reduce expression checks if every element of list lst1
> is present in list lst2. It works as expected for integer lists but
> for lists of strings, it always returns False.
>
> reduce( lambda x,y: (x in lst2) and (y in lst2), lst1)
Possibly this:
>>> True in [3, 1, 4]
True
>>> True in ["3", "1", "4"]
False
Since reduce(f, [a, b, c]) == f(f(a,b),c), your x will be True or
False except in the innermost call where it is the first element of
the list being reduced.
It doesn't really work with integers either. Only in certain special
cases: very short lst1, or True in lst2.
> Moreover, for the lists of strings the following for-loop gives
> correct results when the above reduce expression doesn't.
>
> isSublist = True
> for i in lst1:
> isSublist = isSublist and (i in lst2)
> if not isSublist:
> isSublist = False
> break
>
> Can someone help me understand why?
Consider reduce(lambda x, y: x and (y in whatever), ys, True).
Maybe also consider all(y in whatever for y in ys).
More information about the Python-list
mailing list