python - 提高代码可读性,让python脚本更优雅

标签 python if-statement refactoring switch-statement

有哪些代码结构/编程技术可以避免这种情况:

  if url.netloc  == "www.youtube.com" or "youtu.be" or "soundcloud.com or //
  "instagram.com" or "vine.co" or ETC ETC
     do XYZ

最佳答案

下一行

url.netloc == "www.youtube.com" or "youtu.be" or "soundcloud.com" or "instagram.com"

如下所示:

(url.netloc == "www.youtube.com") or ("youtu.be") or ("soundcloud.com") or ("instagram.com")

它总是产生 True,因为如果用作谓词,非空字符串将被视为真值。

使用 in 代替如下:

if url.netloc in ("www.youtube.com", "youtu.be", "soundcloud.com", "instagram.com", ..):

也可以使用,但需要多次重复或url.netloc ==

关于python - 提高代码可读性,让python脚本更优雅,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19701137/

相关文章:

c - 预期变量没有变化,但一元运算符即使在 false if 语句中也能工作。为什么这样?

c# - ConvertAll<Guid>(Guid.Parse) 是如何工作的?

mysql - 如何减少单个查询中冗余的MySQL函数调用?

python - 从 Unicode 字符串创建 xml 节点(不支持编码声明)?

python - 同时运行多个预训练的 Tensorflow 网络

python - 在 Python Tkinter GUI-PY_VAR21 错误中使用 DataFrame 的多个动态选项菜单

Python使用pandas将numpy数组插入sqlite3数据库

c++ - &&条件的执行方向

python - 多个 IF 和 ELIF 条件 [Python]

performance - 哪个更快?比较还是赋值?