我可以知道如何才能得出预期的结果。我使用“if”语句挣扎了一个小时但没有发生任何事情。
books = [{'title':'Angels and Demons'},{'title':''},{'title':'If'},{'title':'Eden'}]
authors = [{'author':'Dan Brown'},{'author':'Veronica Roth'},{'author':''},{'author':'James Rollins'}]
for i, book in enumerate(books):
print(book, authors[i])
expected result:
({'title': 'Angels and Demons'}, {'author': 'Dan Brown'})
({'title': 'Eden'}, {'author': 'James Rollins'})
答案 0 :(得分:2)
您想要的可能是排除标题或作者为空字符串的对。
books = [{'title':'Angels and Demons'},{'title':''},{'title':'If'},{'title':'Eden'}]
authors = [{'author':'Dan Brown'},{'author':'Veronica Roth'},{'author':''},{'author':'James Rollins'}]
for book, author in zip(books, authors):
if book["title"] and author["author"]:
print(book, author)
# or
[(book, author) for book, author in zip(books, authors) if book["title"] and author["author"]]
答案 1 :(得分:1)
使用List Comphersion
[(books[i],authors[i]) for i,v in enumerate(books) if books[i]['title'] and authors[i]['author']]
输出:
[({'title': 'Angels and Demons'}, {'author': 'Dan Brown'}), ({'title': 'Eden'}, {'author': 'James Rollins'})]
答案 2 :(得分:1)
您问题的一行代码
In [3]: [(book, author) for book, author in zip(books,authors) if book['title'] and author['author']]
Out[3]:
[({'title': 'Angels and Demons'}, {'author': 'Dan Brown'}),
({'title': 'Eden'}, {'author': 'James Rollins'})]
答案 3 :(得分:-1)
books = [{'title':'Angels and Demons'},{'title':''},{'title':'If'},{'title':'Eden'}]
authors = [{'author':'Dan Brown'},{'author':'Veronica Roth'},{'author':''},{'author':'James Rollins'}]
for i, book in enumerate(books):
if book['title'] != '':
print(book, authors[i])
这应该有效