In this example:
sorted_data = [files.data[ind] for ind in sort_inds] May someone please provide an explanation as to how the expression behind the for loop is related or how it is working, thanks.
In this example:
sorted_data = [files.data[ind] for ind in sort_inds] May someone please provide an explanation as to how the expression behind the for loop is related or how it is working, thanks.
It's called a List Comprehension
In other words
sorted_data = [files.data[ind] for ind in sort_inds] is equivalent to:
sorted_data = [] for ind in sort_inds: sorted_data.append(files.data[ind]) It's just a lot more readable using the comprehension
ok so here is a simple example:
say i have a list of ints:
nums = [1,2,3] and i do this:
[i**2 for i in nums] it will output:
[1, 4, 9] this is equivalent to this: for i in nums: list.append(i**2)
because it iterated through the list and squared each item in the list
another example:
say i have a list of strings like this:
list1 = ['hey, jim','hey, pam', 'hey dwight'] and I do this:
[phrase.split(',') for phrase in list1] this will output this list:
[['hey', ' jim'], ['hey', ' pam'], ['hey dwight']] this is equivalent too:
for phrase in list1: new_phrase = phrase.split(',') list.append(new_phrase) it went through and made a list out of each item but it used split on each item
its basically a compacted for loop and instead of using append() it just creates the list!. it is much more readable and takes less lines
learn more here