python - 单词列表中的两个元素
问题描述
我有这样的功能:
def ladderLength(self, beginWord, endWord, wordList):
"""
:type beginWord: str
:type endWord: str
:type wordList: List[str]
:rtype: int
"""
if (endWord not in wordList) or (beginWord not in wordList):
return 0
多个布尔操作很麻烦。
if (endWord not in wordList) or (beginWord not in wordList):
return 0
如何将其简化为清晰简洁?
解决方案
如果您的所有if
-block 都是这样的:
if (endWord not in wordList) or (beginWord not in wordList):
return 0
else: # <- I am assuming this, see Note 1
return 1
然后您可以将整个内容替换为:
return int(all(x in wordList for x in (endWord, beginWord)))
注1
没有
else
子句通常很好,但在您的情况下,您将有一个可能返回0
或None
不是最佳\推荐的函数。如果可以,请按照上面的方法重新设计它。如果不是,我不会费心改变条件。您拥有的那个可读性很强,没有比这更好的替代品了。当然你可以这样做:
if not all(x in wordList for x in (endWord, beginWord)): return 0
但仅此而已。
推荐阅读
- syntax-error - 为什么即使我有空列表的后备,也会返回错误“无法读取未定义 [] 的属性 'car'”?
- javascript - 有没有办法既解构函数参数又保留对参数的命名引用?
- r - rpy2应计问题('InstalledSTPackage'对象没有属性'n')
- python-3.x - 使 `matplotlib.pyplot.plot()` 与 `PeriodIndex 一起工作
- android - 构建android应用程序包时如何修复“缺少按需模块的标题”?
- python - 由于用完所有 RAM,将大型 Pandas df 文本数据保存到磁盘会使 Colab 崩溃。有解决方法吗?
- windows - 为什么函数 LdrRegisterDllNotification 的第一个参数必须为零?
- swift - 如何在swift中保持自定义单元格中记录/记录停止按钮的行为一致?
- css - 自动展开所有 PrimeNG Accordion 面板以进行打印
- ethereum - 这种逻辑在以太坊中可行吗?