languages = ["HTML", "JavaScript", "Python", "Ruby"]
嗨,我正试图在python中学习lambda,我想知道我是否想要过滤掉Python中的#'列表项,为什么我只能使用
print filter(lambda x: x[2], languages)
仍会返回整个列表,并且必须使用
print filter(lambda x: x == 'Python', languages)
谢谢!
答案 0 :(得分:1)
当您应用过滤器功能时,您必须提供一个条件,当满足时返回该值。
print filter(lambda x: x[2], languages)
在第一个过滤器中,x [2]在每种情况下都为真,因为X得到值HTML,因此,x [2]将是M,依此类推。这就是它给出所有价值的原因。
在第二种情况下,您已经给出了条件 x =='Python',因此它会为您提供正确的结果。
答案 1 :(得分:1)
filter
为for
循环。 print filter(lambda x: x[2], languages)
相当于
result = []
for x in languages:
if x[2]:
result.append(x)
print result
请注意,这不是调用languages[2]
Python
,而是调用x[2]
,if 'M':
'HTML'
,if 'v'
'Javascript'
对于True
,依此类推 - 因为这些字符串都是非空的,所以它们被评估为result
,因此被添加到print filter(lambda x: x == 'Python', languages)
。
相反,result = []
for x in languages:
if x == 'Python':
result.append(x)
print result
相当于
languages
在'Python'
上循环,附加与{{1}}匹配的项目,这是所需的效果。
答案 2 :(得分:0)
要过滤掉'Python',请使用!=
(非等于)运算符,如下所示。
print filter(lambda x: x != 'Python', languages)
答案 3 :(得分:0)
为什么不使用列表推导呢?
//using id and other attribute
input#id[attribute=value]
//using classname and other attribute
input.classname[attribute=value]
//using id, classname and other attribute
input#id.classname[attribute=value]
//using three different attributes
input[attribute1=value][attribute2=value][attribute3=value]
它比过滤器更清洁,更快,因为你正在使用lambda,for more info