Python 有条件地赋值(具有多个条件)
作为原问题的后续问题: 我想知道我是否可以扩展这个if语句:Python 有条件地赋值(具有多个条件),python,Python,作为原问题的后续问题: 我想知道我是否可以扩展这个if语句: with open(bom_filename, 'r') as my_file: file_array = [word.strip() for word in my_file if word.startswith("/")] 包括和第二个条件: with open(bom_filename, 'r') as my_file: file_array = [word.strip() for word in my_fil
with open(bom_filename, 'r') as my_file:
file_array = [word.strip() for word in my_file if word.startswith("/")]
包括和第二个条件:
with open(bom_filename, 'r') as my_file:
file_array = [word.strip() for word in my_file if (word.startswith("/")) & not(word.endswith("/"))]
这会产生一个语法错误,但我希望有一些可供选择的语法我可以使用
with open(bom_filename, 'r') as my_file:
file_array = [word.strip() for word in my_file if (word.startswith("/") and not(word.strip().endswith("/")))]
你需要改变
if (word.startswith("/")) & not(word.endswith("/"))
到
或删除额外括号:(根据@viraptor的建议)
请注意,if(…)
,…
必须包含所有逻辑,而不仅仅是if(word.startswith(“/”)
。并用和
替换按位运算符和
你需要改变
if (word.startswith("/")) & not(word.endswith("/"))
到
或删除额外括号:(根据@viraptor的建议)
请注意,
if(…)
,…
必须包含所有逻辑,而不仅仅是if(word.startswith(“/”)
。并将&
这是一个位运算符替换为和您是否记住word.strip()
将在测试后执行,以便“/abc”
不会通过?您是否记住word.strip()
将在测试后执行,以便“/abc”
未通过?在条件检查中字符串的结尾尚未剥离,因此您需要执行类似于word.strip().endswith(“/”)的操作,或者如果您只是剥离一个尾行,则需要执行word.endswith(“/\n”)。查看re模块,了解如何使用正则表达式对字符串执行更复杂的模式匹配,例如re.match(“^\/.\/$”,word.strip()),也不需要大多数括号。它可以是。。。如果word.starswith(“/”)而不是word.endswith(“/”)
@mtadd很好的点,更新以反映OP想要检查“/”排除任何可能的“\n”字符串的结尾在条件检查中还没有被剥离,因此您需要执行类似于word.strip().endswith(“/”)的操作,或者如果您只是剥离一个尾行,则需要执行word.endswith(“/\n”)。查看re模块,了解如何使用正则表达式对字符串执行更复杂的模式匹配,例如re.match(“^\/.\/$”,word.strip()),也不需要大多数括号。它可以是。。。如果word.starswith(“/”)而不是word.endswith(“/”)
@mtadd良好点,则已更新以反映OP希望检查“/”排除任何可能的“\n”
if word.startswith("/") and not word.strip().endswith("/")