为这个模糊的标题提前道歉.我不知道该如何表达我遇到的情况.
想象一下,在变量title_author
中,一本书的标题和作者在一起,用-
隔开.你从网上刮取了这些信息,所以很可能这个项目是None
.显然你想把标题和作者分开,所以你会使用split.但如果title_author
一开始没有,你只希望title
和author
都是None
.
我认为以下是一个很好的方法:
title_author = "In Search of Lost Time - Marcel Proust"
title, author = title_author.split("-", 1) if title_author else None, None
print(title, author)
# ['In Search of Lost Time ', ' Marcel Proust'] None
但令我惊讶的是,现在title
是分裂的结果,author
是None
.解决方案是通过括号显式指示else子句是元组.
title, author = title_author.split("-", 1) if title_author else (None, None)
print(title, author)
# In Search of Lost Time Marcel Proust
为什么会这样?导致第一个案件结果的执行顺序是什么?