列表理解与* args [英] List comprehension with *args

查看:377
本文介绍了列表理解与* args的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to write a function to return a set of strings using python´s list comprehension if any of the passed arguments is in the list. However, it throws requires string as left operand, not tuple, and when trying with another for loop it throws local variable j referenced before assignment

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循环,但我正在尝试使用列表理解。任何提示?谢谢。

Ï could surely do it with for loops but I am trying to use list comprehension. Any hints? Thanks.

推荐答案

你几乎就在那里:

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 扩展到其元素中。

You're just missing one more for to expand the tuple args into its elements.

这篇关于列表理解与* args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆