繁体   English   中英

带有多个 AND 运算符的 IF 语句

[英]IF statement with multiple AND operators

我的代码中有以下行,效果很好,但看起来很丑。

if not line.startswith("<ul>") and not line.startswith("<ol>") and not line.startswith("<li>"):

有没有更好的方法来写这一行?

谢谢

使用正则表达式

import re

if not re.match("^<ol>|^<ul>|^<li>", line):

您可以将any与列表推导式或生成器一起使用:

if not any(line.startswith(tag) for tag in ['<ul>', '<ol>', '<li>']):

如果可迭代对象的任何元素为真,则使用any()返回 True。 如果可迭代对象为空,则返回 False。

if not any(line.startswith(x) for x in ["<ul>", "<ol>", "<li>"]):

不用说,有多种方法可以做到这一点(就像编码中的任何事情一样)。 但是,如果您打算稍后再次使用这些标签,另一种方法是创建一个包含这些标签的列表,然后在需要时引用该列表。 IE

tags = ["<ul>", "<ol>", "<li>"]
#your code here
if line.startswith not in tags:
    #your code here

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM