So I have been liking to have my code more clean and I have been stuck into something that might be very easy to do.
Basically what I have done is currently:
for raw_product in r.json().get('data'):
if raw_product.get('countdown') is False:
print(raw_product.get('url'))
and I have been trying to figure out how to make it to one liner. So far I have only come to
test = ['{}'.format(raw_product.get('url')) for raw_product in r.json().get('data')]
however inside the one liner, there is missing the if statement and I wonder if it possible to apply the if statement inside the ['{}'.format(raw_product.get('url')) for raw_product in r.json().get('data')]
?
Try this generator :
gen = (repr(x.get('url')) for x in r.json().get('data') if not x.get('countdown'))
Or list :
li = [repr(x.get('url')) for x in r.json().get('data') if not x.get('countdown')]
What makes thise code not clean, is not the comprehension, but this 'get' methods. Compare that to :
li = [x.url for x in r.json_data if not x.countdown]
. Is kind of clearer.
I'm not sure it's cleaner, but you can use a generator expression with an if
filter to get this kind of pattern in one line:
[ print(rp.get('url')) for rp in r.json().get('data') if rp.get('countdown') is False ]
Note that this has the inefficiency of creating and remembering a whole list of None
values (the result of every print
call).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.