Returns values from a for loop in python
Solution 1
A one liner would use list or generator comprehensions, see Blair's answer.
An adaption of your current code would suit the yield keyword, which allows you to construct a generator function like this:
def coffee_filter(beans):
for bean in beans:
if bean.type == 'coffee':
yield bean
for bean in coffee_filter(beans):
print "coffee from %s" % bean.country
Since python allows you to define functions pretty much anywhere, this is really useful.
Solution 2
'\n'.join([str(bean) for bean in beans if bean.type == 'coffee'])
jbcurtin
I'm just here to learn how to do things more ways then one.
Updated on March 29, 2021Comments
-
jbcurtin over 3 years
I'm trying to figure out the syntax for passing arguments from one list or dict to another in the for loop syntax.
The desired result I'm looking for is this:
for bean in beans: if bean.type == 'coffee': print bean
Only, instead of printing to stdout, I'd like to collect that string data and append it to another list. Eventually flattening the list.
The kicker, I want to perform this in a single line.
I know of the
''.join()
method, I'm looking for this result so I can filter the results from the for-in loop.