Python:从多个词典列表中筛选空字符串
问题描述:
我可以知道如何提出我的预期结果。我正在使用“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'})
答
你想可能是排除一对标题或作者为空字符串什么。
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
答
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])
这应该工作
答
使用列表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'})]
答
一行代码
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',以便更好地优化内存。 –
您的代码甚至没有一个if语句。如果你没有正确解释,我们如何帮助你?详情请阅读https://*.com/help/how-to-ask – Mikkel