[英]Multiple if conditions in a list comprehension
I have a list with links and was trying to filter those and got stuck. 我有一个包含链接的列表,并试图过滤它们并陷入困境。 I was able to write a function for multiple if statements explicitly but was looking to write it directly in the list comprehension.
我能够为多个if语句显式编写一个函数,但希望直接在列表理解中编写它。
I have tried multiple ways (i.startswith(), "https" in i)
to write it but couldn't figure it out. 我尝试了多种方式
(i.startswith(), "https" in i)
编写它,但无法弄清楚。
This is the list comprehension: 这是列表理解:
[i.a.get('href') for i in link_data if i != None]
Output: 输出:
['/gp/redirect.html/ref=as',
'https://www.google.com/',
'https://www.amazon.com/',
'/gp/redirect.html/ref=gf']
I only require links which starts with https
. 我只需要以
https
开头的链接。
How can I write this if condition in my list comprehension given above? 如果上面给出的清单理解中的条件该如何写? Any help is appreciated.
任何帮助表示赞赏。
You can combine two conditionals with and
-- but list comprehensions also support multiple if
s (which get evaluated with and
) 您可以将两个条件与
and
组合使用-但列表推导还支持多个if
s(使用and
评估)
Here's two options for what you want: 这是您想要的两个选项:
# combining conditions with `and`
output = [
i.a.get('href') for i in link_data
if i is not None and i.a.get('href').startswith('https')
]
# combining conditions with multiple `if`s
output = [
i.a.get('href') for i in link_data
if i is not None
if i.a.get('href').startswith('https')
]
(note these were indented for clarity, the whitespace between the [
and ]
is not important) (请注意,为清楚起见,将它们缩进,
[
和]
之间的空格并不重要)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.