简体   繁体   English

使用lambda过滤字符串列表

[英]filtering a list of strings using lambda

I have a list like, 我有一个清单,

old_list=["a_apple","b_banana","c_cherry"]

and I want to get new list using lambda . 我想使用lambda获取新列表。

new_list=["apple","banana","cherry"]

I tried but it doesn't work as I expected. 我试过了,但是没有按预期工作。 here is what I wrote. 这是我写的。

new_list=filter(lambda x: x.split("_")[1], old_list)

what is the problem ? 问题是什么 ?

Try this: 尝试这个:

Python-2 : Python-2

In [978]: old_list=["a_apple","b_banana","c_cherry"]

In [980]: new_list = map(lambda x: x.split("_")[1], old_list)

In [981]: new_list
Out[981]: ['apple', 'banana', 'cherry']

Python-3 : Python-3

In [4]: new_list = list(map(lambda x: x.split("_")[1], old_list))

In [5]: new_list
Out[5]: ['apple', 'banana', 'cherry']

Using list comprehensions 使用列表推导

lst=["a_apple","b_banana","c_cherry"]
[i.split("_")[1] for i in lst]

Output: 输出:

['apple', 'banana', 'cherry']

You can map the list with a lambda function: 您可以使用lambda函数map列表:

list(map(lambda s: s.split('_')[1], old_list))

This returns: 返回:

['apple', 'banana', 'cherry']

By using lambda and map: 通过使用lambda和map:

li=["a_apple","b_banana","c_cherry"]

new_li = map(lambda x: x.split('_')[1], li)
print (list(new_li))
# ['apple', 'banana', 'cherry']

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

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