frankV
frankV

Reputation: 5513

Python lambda to print formatted nested list

Practicing a couple things: lambda functions and string manipulations. I want to find the most efficient ways of doing this without importing anything.

so here's a short script that reorders a word alphabetically:

def alphabeticalOrder(word):
    lst = [l for l in word]
    return sorted(lst)


def main ():
    word = raw_input('enter word: ')
    print "".join(alphabeticalOrder(word))


if __name__ == '__main__':
    main()

and I wanted to do this for all words in a sentence:

def alphabeticalOrder(line):
    lst = []
    for word in line.split(" "):
        lst.append(sorted(list(word)))
    print lst     # trouble here

def main ():
        line = raw_input('enter sentence: ')
        print alphabeticalOrder(line)

if __name__ == '__main__':
    main()

So my question is; can you write a lambda function to iterate through the nested lists in lst that prints out each item as a just a string of alphabetically reordered words?

Upvotes: 0

Views: 1163

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

An improved version of your first approach to work for sentences:

def alphabeticalOrder(word):
    return "".join(sorted(lst)) #return the sorted string


def main ():
    sent = raw_input('enter sentence: ')
    print " ".join(map(alphabeticalOrder,sent.split())) #map alphabeticalOrder to each
                                                        #word in the sentence


if __name__ == '__main__':
    main()

output:

enter sentence: foo bar spam eggs
foo abr amps eggs

Upvotes: 1

MostafaR
MostafaR

Reputation: 3695

You want this:

' '.join([''.join(sorted(word)) for word in sentence.split(' ')])

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121584

List comprehensions are much easier here:

' '.join([''.join(sorted(word)) for word in sentence.split()])

Note that we can pass the string to sorted() directly.

A lambda is nothing more than a function with a single expression, which can be defined as an expression itself; here I assign the lambda result to a variable first:

alphabeticalWord = lambda w: ''.join(sorted(word))

' '.join([alphabeticalWord(word) for word in sentence.split()])

Upvotes: 3

Related Questions