列表中的多个if条件

2024-04-16 18:41:39 发布

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

我有一个与链接列表,并试图过滤这些卡。我能够为多个if语句显式地编写一个函数,但希望直接在列表中编写它。你知道吗

我试过多种方法(i.startswith(), "https" in i)来写它,但都想不出来。你知道吗

以下是列表:

[i.a.get('href') for i in link_data if i != None]

输出:

['/gp/redirect.html/ref=as',
'https://www.google.com/',
'https://www.amazon.com/',
'/gp/redirect.html/ref=gf']

我只需要以https开头的链接。你知道吗

我如何在上面给出的理解列表中写出这个if条件?感谢您的帮助。你知道吗


Tags: 方法函数inhttpscomref列表if
1条回答
网友
1楼 · 发布于 2024-04-16 18:41:39

可以用and组合两个条件,但列表理解也支持多个if(用and计算)

这里有两个选项供您选择:

# 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')
]

(注意,为了清晰起见,这些是缩进的,[]之间的空白并不重要)

相关问题 更多 >