在python中构建列表时忽略元素 [英] Ignore an element while building list in python

查看:82
本文介绍了在python中构建列表时忽略元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用[f(char) for char in string]语法从python中的字符串构建列表,并且我希望能够忽略(不插入列表)等于(c1>)的f(x)值

I need to build a list from a string in python using the [f(char) for char in string] syntax and I would like to be able to ignore (not insert in the list) the values of f(x) which are equal to None.

我该怎么做?

推荐答案

我们可以创建一个子查询".

We could create a "subquery".

[r for r in (f(char) for char in string) if r is not None]

如果您还允许忽略所有False值(0,False,None等),则可以使用filter:

If you allow all False values (0, False, None, etc.) to be ignored as well, filter could be used:

filter(None, (f(char) for char in string) )
# or, using itertools.imap,
filter(None, imap(f, string))

这篇关于在python中构建列表时忽略元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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