1
votes

I have the following list:

bananas = ['7,2,1 : Banana', 'Z : Banana', 'L,D : Banana']

I am would like to use Python's high order functions to derive the following:

[['7', '2', '1'], ['Z'], ['L', 'D']]

I have written this:

bananas_stripped = map(lambda x: [x.split(':')[0]], bananas)

...which produces this:

[['7,2,1 '], ['Z '], ['L,D ']]

I can apply another HOF like so:

test = map(lambda x: x[0].split(','), bananas_stripped)

But I can't figure out how to write it all in one function, i.e. I would like to do it all within bananas_stripped.

3
How about map(lambda x: x.split(':')[0].strip().split(','), bananas)?vaultah
@vaultah yep, that's great. Thanks a lot. Thanks for the strip() too.dstar

3 Answers

1
votes

Just making vaultah's answer into a proper answer.

map(lambda x: x.split(':')[0].strip().split(','), bananas)

0
votes
bananas_stripped = [['7,2,1 '], ['Z '], ['L,D ']]
new_bananas_stripped = []
for item in bananas_stripped:
    item_string = item[0].replace(" ", "")
    item_string = item_string.split(',')
    new_bananas_stripped.append(item_string)
print(new_bananas_stripped)

And this will give the output

[['7', '2', '1'], ['Z'], ['L', 'D']]

Sorry i'm not so good at simplifying the code down into one line.

-1
votes

I think this will work:

bananas_stripped = map(lambda x: [x.strip().split(",") for x in [x.split(':')[0]]], bananas)