我可以在列表理解中的条件中使用 "or" 吗?

Can I use "or" in a condition inside a list comprehension?

有没有办法在列表推导式的条件中加入“或”? 我想“压缩”这段代码:

# In this lines of code I take a certain text_file.txt and create a list with each word, without 
# considering the lines that starts with "#" OR empty lines
for line in text_file:
    if not line.startswith("#") or line != "\n":
       word_list = ([word for word in line.split()])

所以我认为可以这样做:

[[word for word in line.split()] for line in text_file if not line.startswith("#") or line != "\n"]

当然上面的代码没有return我期望的输出。

有没有办法像我在那里写的假设列表理解一样?

谢谢!

是的,您可以在列表理解中使用 'or',尝试:

mylist  = [1,2,3,4,5,6,7,8,9]
print([i for i in mylist if i >6 or i <3])
>>>[1, 2, 7, 8, 9]

您的代码中的问题是您使用了 'or' 但应该使用 'and':

mylist  = ["1 2 3","2 3 4","\n","1 2 4","#somecomment"]
print([i.split(" ") for i in mylist if i[0] !="#" and i !="\n"])
>>>[['1', '2', '3'], ['2', '3', '4'], ['1', '2', '4']]