如何使用python中的lambdas从不同的字符串中提取所需的字符串列表

时间:2015-05-20 13:45:57

标签: python list list-comprehension

S = [u'BIGSQL_WORKER', u'DATANODE', u'FLUME_HANDLER', u'HBASE_CLIENT', u'HBASE_REGIONSERVER', u'HCAT', u'HDFS_CLIENT', u'HIVE_CLIENT', u'MAPREDUCE2_CLIENT', u'NODEMANAGER', u'OOZIE_CLIENT', u'PIG', u'SLIDER', u'SOLR', u'SPARK_CLIENT', u'SQOOP', u'YARN_CLIENT', u'ZOOKEEPER_CLIENT', u'ZOOKEEPER_SERVER']

我想删除其中包含'CLIENT'的字符串,

F = map(lambda x: x if 'CLIENT' not in x else None, S)
F = [u'BIGSQL_WORKER', u'DATANODE', u'FLUME_HANDLER', None, u'HBASE_REGIONSERVER', u'HCAT', None, None, None, u'NODEMANAGER', None, u'PIG', u'SLIDER', u'SOLR', None, u'SQOOP', None, None, u'ZOOKEEPER_SERVER']

我尝试过传递但是在lambda内部没有任何作用,任何想法?

2 个答案:

答案 0 :(得分:3)

尝试list comprehension,这是非常通用的,可以用于这些事情:

[s for s in S if 'CLIENT' not in s]

答案 1 :(得分:1)

列表理解可能就是您要找的内容,但您也可以使用filter [docs]而不是地图:

In [77]: filter(lambda s: 'CLIENT' not in s, S)
Out[77]:
[u'BIGSQL_WORKER',
 u'DATANODE',
 u'FLUME_HANDLER',
 u'HBASE_REGIONSERVER',
 u'HCAT',
 u'NODEMANAGER',
 u'PIG',
 u'SLIDER',
 u'SOLR',
 u'SQOOP',
 u'ZOOKEEPER_SERVER']