有条件地赋值(有多个条件)

2024-04-26 23:42:49 发布

您现在位置:Python中文网/ 问答频道 /正文

作为原问题的后续: Python: Stripping elements of a string array based on first character of each element

我想知道我是否可以扩展这个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_file if (word.startswith("/")) & not(word.endswith("/"))]

这产生了一个语法错误,但我希望有一些替代语法,我可以使用!你知道吗


Tags: ofinforifmyaswithopen
1条回答
网友
1楼 · 发布于 2024-04-26 23:42:49
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("/"))

if (word.startswith("/") and not(word.strip().endswith("/"))) 

或者去掉括号:(根据@viraptor的建议)

if word.startswith("/") and not word.strip().endswith("/") 

注意if(...)...必须包含所有逻辑,而不仅仅是if(word.startswith("/"))。并用and替换位运算符&。你知道吗

相关问题 更多 >