Reputation: 785
Can anyone help me understand the following piece of python code:
for i, char in filter(lambda x: x[1] in str1, enumerate(str2)):
# do something here ...
str1 and str2 are strings, I sort of understand that the "lambda x: x[1] in str1" is filtering condition, but why x[1] ?
How can I convert this for loop into a lower level (but easier to understand) python code ?
Thanks
Upvotes: 2
Views: 149
Reputation: 8610
This appears functionality equivalent to:
for i, char in enumerate(str2):
if char in str1:
# do something here
filter
is taking a list of tuples consisting of the index and elements of str2
, filtering out those elements that do not appear in str1
, then returning a iterable of the remaining indices and elements from str2
.
Upvotes: 4
Reputation: 39403
Because of enumerates
.
Enumerates returns tuples of (index, value)
for an iterable of values.
x
is a tuple of index, char.
I would write lambda (index, char): char in str1
for clarity
Upvotes: 0