2017-09-02 9 views
0

私の期待する結果をどうやって思いつくのか分かりますか?私は "if"ステートメントを使ってこれを1時間苦労しているが、何も起こらなかった。Python:複数の辞書リストから空文字列をフィルタリングする

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'}) 
+1

を。あなたが正しく説明しなければ、どうすればあなたを助けることができますか?詳細についてはhttps://stackoverflow.com/help/how-to-askをお読みください – Mikkel

答えて

2

を動作するはずです。

一覧Comphersion

[(books[i],authors[i]) for i,v in enumerate(books) if books[i]['title'] and authors[i]['author']] 

出力使用

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"]] 
+0

はい、これは私が探しているものです。ありがとうございました。 – Jom

-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]) 

これは、タイトルや著者が空の文字列であるペアを除外される可能性があります欲しい

1

:あなたのコードでも、if文を持っていない

[({'title': 'Angels and Demons'}, {'author': 'Dan Brown'}), ({'title': 'Eden'}, {'author': 'James Rollins'})] 
1

あなたの問題の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'})] 
+0

メモリをより良く最適化するために、値が多い場合は 'generator'を使用できます。 –

関連する問題