Reputation: 9213
I can write the append line two ways. Neither produce the desired result. Is there a way to wrap this up in 1 line?
Option 1:
row.append(x[1] for x in emails if x[0] == row[1])
Yields:
[['project1', 'email1', <generator object <genexpr> at 0x0227D670>], ['project1', 'email2', <generator object <genexpr> at 0x022EB8A0>]]
Option 2:
row.append([x[1] for x in emails if x[0] == row[1]])
Yields:
[['project1', 'email1', ['[email protected]']], ['project1', 'email2', ['[email protected]']]]
Desired Result:
[['project1', 'email1', '[email protected]'], ['project1', 'email2', '[email protected]']]
Code:
emails = [['email1','[email protected]'],['email2','[email protected]']]
projects = [['project1', 'email1'], ['project1', 'email2']]
for row in projects:
row.append(x[1] for x in emails if x[0] == row[1])
print projects
Upvotes: 2
Views: 77
Reputation: 113844
In your existing code, replace this one line:
row.append(x[1] for x in emails if x[0] == row[1])
With:
row.extend(x[1] for x in emails if x[0] == row[1])
Alternatively, eliminating the loop and condensing the code all into one line:
>>> projects = [ row + [x[1] for x in emails if x[0] == row[1]] for row in projects ]
>>> print projects
[['project1', 'email1', '[email protected]'], ['project1', 'email2', '[email protected]']]
Upvotes: 4
Reputation: 180411
emails = [['email1','[email protected]'],['email2','[email protected]']]
projects = [['project1', 'email1'], ['project1', 'email2']]
from itertools import chain
print([list(set((chain.from_iterable(ele)))) for ele in zip(emails,projects)])
[['email1', '[email protected]', 'project1'], ['email2', 'project1', '[email protected]']]
Or:
print([list(set(ele).union(projects[ind])) for ind, ele in enumerate(emails)])
Or:
print([projects[ind] + [ele for ele in sub if ele not in projects[ind]] for ind, sub in enumerate(emails)])
All the different versions will work for multiple items not just checking against a single element.
Upvotes: 1