简体   繁体   English

使用理解获取满足某些条件的列表元素

[英]Getting list elements satisfying some criteria using a comprehension

I have a list like this:我有一个这样的列表:

foolist = ['foo   bar', 'foo', 'bar' 'foo bar']

I want the number of foo s in that list, without using regex.我想要该列表中foo的数量,而不使用正则表达式。 Is there a simpler way to do it than below, using one line?有没有比下面更简单的方法,使用一条线?

print(len([i for i in [ 'foo' in line for line in foolist ] if i == True]))

The above is interesting, but it also makes my skin crawl in the way that nested ternary operators would.上面的内容很有趣,但它也让我的皮肤像嵌套的三元运算符那样爬行。

This is a little shorter: use map to transform foolist to a list of 1's and 0', then sum them up:这有点短:使用mapfoolist转换为 1's 和 0' 的列表,然后将它们sum

sum(map(lambda x: 1 if 'foo' in x else 0, foolist))

Update: or even shorter:更新:甚至更短:

len(tuple(filter(lambda x: 'foo' in x, foolist)))

My brain finds comprehensions incomprehensible when they are not simple so I move on to map/reduce/filter functions:)当理解不简单时,我的大脑会发现它们难以理解,所以我继续使用映射/归约/过滤函数:)

UPDATE: Added tuple since in Python3, len can't count an iterator.更新:添加了tuple ,因为在 Python3 中, len不能计算迭代器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM