At a high level, what I'm trying to accomplish is:
given a list of words, return all the words that do not consist solely of digits
My first thought of how to do that is:
import string
result = []
for word in words:
for each_char in word:
if each_char not in string.digit:
result.append(word)
break
return result
This works fine. To be more Pythonic, I figured - list comprehensions, right? So:
return [word for word in words for char in word if not char in string.digits]
Unfortunately, this adds a copy of word
to the result for each character that isn't a digit. So for f(['foo'])
, I end up with ['foo', 'foo', 'foo']
.
Is there a clever way to do what I'm trying to do? My current solution is to just write an is_all_digits
function, and say [word for word in words if not is_all_digits(word)]
. My general understanding is that list comprehensions allow this sort of operation to be declarative, and the helper function is plenty declarative for me; just curious as to whether there's some clever way to make it one compound statement.
Thanks!
Explanation: The required list comprehension will print a whole number, less than 20, provided that the number is even. Since the output list should contain zero as well, the answer to this question is: [x for x in range(0, 20) if (x%2==0)].
Introduction. List comprehensions offer a succinct way to create lists based on existing lists. When using list comprehensions, lists can be built by leveraging any iterable, including strings and tuples. Syntactically, list comprehensions consist of an iterable containing an expression followed by a for clause.
A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list. Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.
Because it's a very comprehensive way to describe a sequence (a set in math and other languages, and a list/sequence in Python).
Why not just check the whole string for isdigit()
:
>>> words = ['foo', '123', 'foo123']
>>> [word for word in words if not word.isdigit()]
['foo', 'foo123']
Or, turn the logic other way and use any()
:
>>> [word for word in words if any(not char.isdigit() for char in word)]
['foo', 'foo123']
any()
would stop on the first non-digit character for a word and return True
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With