Python:从多个字典列表中筛选空字符串

时间:2017-09-02 06:58:04

标签: python

我可以知道如何才能得出预期的结果。我使用“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'})

4 个答案:

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

这应该有效