Reputation: 83
I have a list like,
old_list=["a_apple","b_banana","c_cherry"]
and I want to get new list using 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 ?
Upvotes: 0
Views: 823
Reputation: 34086
Try this:
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:
In [4]: new_list = list(map(lambda x: x.split("_")[1], old_list))
In [5]: new_list
Out[5]: ['apple', 'banana', 'cherry']
Upvotes: 2
Reputation: 1824
Using list comprehensions
lst=["a_apple","b_banana","c_cherry"]
[i.split("_")[1] for i in lst]
Output:
['apple', 'banana', 'cherry']
Upvotes: 1
Reputation: 10669
By using lambda and map:
li=["a_apple","b_banana","c_cherry"]
new_li = map(lambda x: x.split('_')[1], li)
print (list(new_li))
# ['apple', 'banana', 'cherry']
Upvotes: 0
Reputation: 107095
You can map
the list with a lambda
function:
list(map(lambda s: s.split('_')[1], old_list))
This returns:
['apple', 'banana', 'cherry']
Upvotes: 1