Python条件判断逻辑错误:无法正确过滤YouTube链接问题
修正Python代码实现过滤非YouTube链接的功能
你的代码存在两处核心逻辑错误,导致无法实现预期功能:
- 遍历逻辑混乱:通过索引遍历列表时,却用
random.choice(fetchurl)随机选取url,导致当前循环的索引对应url和实际判断的url完全不相关,还会重复输出随机内容 - 条件判断错误:
url != fetchurl[i].startswith(...)是将字符串类型的url和startswith返回的布尔值(True/False)做比较,这个逻辑完全不成立,必然导致错误的判断结果
修正后的代码
直接遍历列表中的每个url,判断其是否不以YouTube前缀开头,符合条件则打印:
import random # 原代码漏了导入random,需补上 fetchurl = ["https://www.smithsonianmag.com/science-nature/how-wolves-really-became-dogs-180970014/", "https://www.youtube.com/watch?v=DdPMV7GO8q0", "https://www.npr.org/2013/01/25/170267847/canine-mystery-how-dogs-became-mans-best-friend", "https://www.youtube.com/watch?v=DdPMV7GO8q0", "https://www.youtube.com/watch?v=nDt0HKSdRRw&t=554", "https://www.youtube.com/watch?v=nDt0HKSdRRw&t=554", "https://www.youtube.com/watch?v=DdPMV7GO8q0", "https://www.bbc.com/news/science-environment-40638584", "https://www.youtube.com/watch?v=nDt0HKSdRRw&t=79", "https://www.bbc.com/news/science-environment-40638584", "https://www.newscientist.com/article/2264329-humans-may-have-domesticated-dogs-by-accident-by-sharing-excess-meat/", "https://www.mypet.com/basic-pet-care/dog-mans-best-friend.aspx#:~:text=Scientists%20speculate%20that%20friendship%20bloomed,Those%20Who%20Must%20Be%20Obeyed.", "https://www.youtube.com/watch?v=tggdERc8E6Y&t=11", "https://www.npr.org/2013/01/25/170267847/canine-mystery-how-dogs-became-mans-best-friend"] # 直接遍历列表中的每个url for url in fetchurl: # 判断url是否不以YouTube前缀开头 if not url.startswith("https://www.youtube.com/"): print(url) # 不需要输出"lol"可直接删除else分支 # else: # print("lol")
可选优化:去重输出
如果需要过滤重复的非YouTube链接,可以先将列表转成集合去重,再遍历:
unique_urls = list(set(fetchurl)) for url in unique_urls: if not url.startswith("https://www.youtube.com/"): print(url)
内容的提问来源于stack exchange,提问作者Info Rewind
相关产品推荐
相关产品推荐

