【问题标题】:List comprehension with *args使用 *args 的列表理解
【发布时间】:2017-02-19 21:13:56
【问题描述】:

如果任何传递的参数在列表中,我想编写一个函数来使用 python 的列表推导返回一组字符串。但是,它抛出 需要字符串作为左操作数,而不是元组,并且当尝试使用另一个 for 循环时,它会抛出 在赋值之前引用的局部变量 j

def checkFor(*args):
    return {a['title'] for a in soup.findAll('a') if 'title' in a.attrs and any(args in a['title'])}

def checkFor_(*args):
    return{a['href'] for a in soup.findAll('a') if 'title' in a.attrs and j in a['title'] for i, j in enumerate(args)}

checkFor(a, b, c)

Ï 肯定可以用 for 循环来做到这一点,但我正在尝试使用列表理解。有什么提示吗?谢谢。

【问题讨论】:

    标签: python beautifulsoup iteration list-comprehension


    【解决方案1】:

    你快到了:

    def checkFor(*args):
        return {a['title'] for a in soup.findAll('a') if 'title' in a.attrs and any(arg in a['title'] for arg in args)}
    

    您只是缺少一个 for 来将元组 args 扩展为它的元素。

    【讨论】:

    • 啊,完美!!简洁明了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多