Reputation: 25
May I know how can I come up with my expected result. I'm struggling this for an hour using “if” statement but nothing happened.
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'})
Upvotes: 0
Views: 89
Reputation: 1544
One line code for your problem
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'})]
Upvotes: 1
Reputation: 6475
What you want might be exclude the pair which the title or the author is empty string.
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"]]
Upvotes: 2
Reputation: 3523
Using List Comphersion
[(books[i],authors[i]) for i,v in enumerate(books) if books[i]['title'] and authors[i]['author']]
Output:
[({'title': 'Angels and Demons'}, {'author': 'Dan Brown'}), ({'title': 'Eden'}, {'author': 'James Rollins'})]
Upvotes: 1
Reputation: 1363
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])
This should work
Upvotes: -1