Issue
I have 2 lists of strings and I want to compare and return the strings that have the same length in the same position in each of the string lists. I understand how to do this with loops and comprehensions so I've been trying to do this using zip, lambdas, and filter which I want to practice more but have been running into a wall after endless searching/googling.
list1 = ["aaa", "bb", "c", "wwwww"]
list2 = ["dddd", "xx", "a", "abcd"]
Should return: [("bb", "xx"), ("c", "a")]
Heres what I've been using but doesnt seem to be working:
list(filter(lambda param: len(param) == len(param), zip(list1, list2)))
Solution
Using filter
:
list1 = ["aaa", "bb", "c", "wwwww"]
list2 = ["dddd", "xx", "a", "abcd"]
output = list(filter(lambda z: len(z[0]) == len(z[1]), zip(list1, list2)))
print(output) # [('bb', 'xx'), ('c', 'a')]
Using list comprehension, which I prefer due to readability:
output = [(x, y) for x, y in zip(list1, list2) if len(x) == len(y)]
Answered By - j1-lee
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.