Issue
I have a simple list:
lst1 = ['a', 'b', 'c']
I also have a nested list with the values above plus more:
lst2 = [ ('a',[ 'aaa', 'bbb']), ('b',[ 'xxx', 'yyy']), ('c',['ww', 'mm', 'ii']), ('e',['rr', 'rr', 'tt'])]
I have been trying to match all common elements in lst1 with the ones found in lst2 and create a new nested list with the common elements plus the nested values:
lst3 = [('a',[ 'aaa', 'bbb']), ('b',[ 'xxx', 'yyy']), ('c',['ww', 'mm', 'ii'])]
My code is as follow:
lst3 = []
for i in lst2:
if i in lst1 and lst2[0]:
lst3.append(i)
But lst3 ends up empty after running the loop. Any tips would be appreciated.
thanks
Solution
Problem with your code
You are checking if i in lst1 and lst2[0]:
which never come True
. because ('a',[ 'aaa', 'bbb'])
is not in lst1
.
Solution
lst1 = ['a', 'b', 'c']
lst2 = [ ('a',[ 'aaa', 'bbb']), ('b',[ 'xxx', 'yyy']), ('c',['ww', 'mm', 'ii']), ('e',['rr', 'rr', 'tt'])]
ans = []
for i in lst2:
x = i[0]
if x in lst1:
ans.append(i)
print(ans)
Output
[('a', ['aaa', 'bbb']), ('b', ['xxx', 'yyy']), ('c', ['ww', 'mm', 'ii'])]
Answered By - PSKP
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.