The snippet below is supposed to take in image labels(directory consists of respective labels as file names) in the given directory and plot the image using a subplot.
import os
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
training_hor_dir='./horse-or-human/horses'
training_hum_dir='./horse-or-human/humans'
nrows=4
ncols=4
pic_index=0
fig=plt.gcf()
fig.set_size_inches(ncols*4,nrows*4)
pic_index =8
next_horse_pic=[os.path.join(training_hor_dir,fname)
for fname in training_hor_labels[pic_index-8:pic_index]]
Can someone please walk me through how the following for loop work? What's the core concept behind such a snippet(join statement followed by for loop inside an array ? I can't get my head around it)?
Also, Is it possible to add in furthermore statements after for loop? If so, how? and if not, why?
And how to print fname inside for-loop?
Any help is appreciated. Thanks in advance.
CodePudding user response:
It's called a comprehension
: it's a clever way of creating new data from data you already have. Generally it works like this:
newList = [oldValue * 2 for oldValue in oldList]
Where oldValue * 2
can be replaced with whatever operation you want.
There's lots of other things you can do with comprehensions - too much to list here. Dictionaries, nested comprehensions, and so on. Here's an article to get started.
As for printing (or executing any commands for that matter) technically you can just throw away the new value, like so:
uselessList = [print(item) for item in oldList]
But then the new uselessList
would just be loads of None
s. What I'd do is just use another for loop and print the items out the old fashioned way.