HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Python List Continuation with multiple lambdas applied

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lambdascontinuationwithappliedpythonmultiplelist

Problem

I'm attempting to apply multiple filters and maps to a list and attempted to refactor into something i believe is more readable. In my code, I am reading a file to create a list of terms, then munging it into something I will feed into another script.

Please note my terminology in the title might be wrong, but please feel free to correct.

Originally, I had something that looked like this:

random_substring = lambda word: word[:(random.randrange(len(word) - 2) + 1)]

only_longer_words = lambda word: len(word) > 2 

terms = []

#File manipulation that adds words to terms

terms = filter(only_longer_words, terms)
terms = map(random_substring, terms)
terms = filter(only_longer_words, terms)

#Save terms to file


After refactoring, I created a ChainList which inherits from list:

class ChainList(list):
    def filter(self, function):
        return ChainList(filter(function, self))

    def map(self, function):
        return ChainList(map(function, self))

    def uniquify(self):
        return ChainList(OrderedDict.fromkeys(self))


and use it as such:

terms = ChainList()

working_list = (
    terms.filter(only_longer_words)
         .map(random_substring)
         .filter(only_longer_words) 
         .uniquify()
)


The intent is to make it easy to chain operations on lists. It works, but as a Python beginner, wanted a review.

Solution

The biggest problem with your code was the formatting issues (PEP8 violations), which you already fixed, with the exception of workingList which should be working_list.

Doc strings would be nice.

Instead of "uniquify", perhaps unique or even uniq sounds better.

In your first lambda you used word as the variable, in the second you used x. It would be more natural to unify.

This code doesn't make your ass look fat, I think.

Context

StackExchange Code Review Q#62065, answer score: 3

Revisions (0)

No revisions yet.