我可以用两种方式写出追加线。都没有产生预期的结果。有没有办法将它包装成一行?
选项1:
row.append(x[1] for x in emails if x[0] == row[1])
收率:
[['project1', 'email1', <generator object <genexpr> at 0x0227D670>], ['project1', 'email2', <generator object <genexpr> at 0x022EB8A0>]]
选项2:
row.append([x[1] for x in emails if x[0] == row[1]])
收率:
[['project1', 'email1', ['john@gmail.com']], ['project1', 'email2', ['bill@gmail.com']]]
期望的结果:
[['project1', 'email1', 'john@gmail.com'], ['project1', 'email2', 'bill@gmail.com']]
代码:
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
答案 0 :(得分:4)
在现有代码中,替换以下一行:
row.append(x[1] for x in emails if x[0] == row[1])
使用:
row.extend(x[1] for x in emails if x[0] == row[1])
或者,消除循环并将代码全部压缩成一行:
>>> 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']]
答案 1 :(得分:1)
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']]
或者:
print([list(set(ele).union(projects[ind])) for ind, ele in enumerate(emails)])
或者:
print([projects[ind] + [ele for ele in sub if ele not in projects[ind]] for ind, sub in enumerate(emails)])
所有不同的版本都适用于多个项目,而不仅仅是针对单个元素进行检查。