2017-09-02 45 views
0

我可以知道如何提出我的預期結果。我正在使用「if」陳述掙扎一個小時,但沒有發生任何事情。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

您的代碼甚至沒有一個if語句。如果你沒有正確解釋,我們如何幫助你?詳情請閱讀https://stackoverflow.com/help/how-to-ask – Mikkel

回答

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

使用列表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'})] 
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',以便更好地優化內存。 –

相關問題