inetbion.blogg.se

Python filter list stack overflow
Python filter list stack overflow









With one main "if tree to end all if trees" you will over time end up with a complete mess. Return Īdding new logical checks is suddenly trivial. You could make this a list comprehension and even simpler if you want: def filter_strings_list_comp(strs): Then iterate over that list, checking if any of them return true for the current string.

python filter list stack overflow

Notice how easy it is now to add new check conditions, you just need to make/test a small function and add it to your filter list. This can streamline your main logic significantly (using any again): filters = [contains_numbers, Both these test specific conditions that can be optimized a bit better in single functions. Return words.upper() != wordsįairly straightforward here. def single_word_is_not_all_caps(s):ĭef contains_multiple_words_not_uppercase(s): It will return True if any condition in the list matches. I moved each conditional check into a separate, small function: # Convention: returns true if should be removed, based on criteriaĪny is a great use for things like this.

#Python filter list stack overflow code

oh my! Second it's also difficult to add new checks into if you want other filter conditions.Ĭode like your original code starts out well intentioned but becomes a giant spaghetti mess fairly quickly - you only have three conditions and it's already a complex and hard to read and quickly understand function.

python filter list stack overflow

I took the liberty of rewriting most of this from scratch for a few reasons.įirst, this very difficult to actually test.









Python filter list stack overflow