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', ['john@gmail.com']], ['project1', 'email2', ['bill@gmail.com']]]
Desired Result:
[['project1', 'email1', 'john@gmail.com'], ['project1', 'email2', 'bill@gmail.com']]
Code:
emails = [['email1','john@gmail.com'],['email2','bill@gmail.com']]
projects = [['project1', 'email1'], ['project1', 'email2']]
for row in projects:
row.append(x[1] for x in emails if x[0] == row[1])
print projects
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', 'john@gmail.com'], ['project1', 'email2', 'bill@gmail.com']]
emails = [['email1','john@gmail.com'],['email2','bill@gmail.com']]
projects = [['project1', 'email1'], ['project1', 'email2']]
from itertools import chain
print([list(set((chain.from_iterable(ele)))) for ele in zip(emails,projects)])
[['email1', 'john@gmail.com', 'project1'], ['email2', 'project1', 'bill@gmail.com']]
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.