Python:从多个字典列表中筛选空字符串
请问我怎样才能得出预期的结果。我用“如果”语句挣扎了一个小时,但什么也没发生Python:从多个字典列表中筛选空字符串,python,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 enumera
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])
这应该行得通
这应该可以您想要的可能是排除标题或作者为空字符串的对
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"]]
您想要的可能是排除标题或作者为空字符串的对
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"]]
使用列表压缩
[(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'})]
使用列表压缩
[(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'})]
一行代码解决您的问题
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'})]
您的代码甚至没有if语句。如果你解释得不好,我们怎么帮你?请阅读详细信息您的代码甚至没有if语句。如果你解释得不好,我们怎么帮你?请阅读详细信息,这是我要找的。谢谢。是的,这就是我要找的。谢谢。如果有很多值,您可以使用
generator
,以便更好地优化内存。如果有很多值,您可以使用generator
,以便更好地优化内存。