Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can someone explain me this
#1
hello,

I am new to python.
So, can some one explain me what does the last two line of the following do?

line_prof_lesser_idx = np.where(line_prof <= min_depth)
line_prof_lesser.append(len(line_prof_lesser_idx[0]))

mov_av_contact_idx_lesser.append(int(mov_av_data[i].index(max_grad[i])))
            
mov_av_contact_idx = [mov_av_contact_idx_lesser + line_prof_lesser for mov_av_contact_idx_lesser,line_prof_lesser in zip(mov_av_contact_idx_lesser, line_prof_lesser)]


User has been warned for this post. Reason: No BBcode, post in incorrect forum
Reply
#2
For the penultimate line, the integer of whatever mov_av_data[i].index(max_grad[i]) references is appended to the list mov_av_contact_idx_lesser.

The last line uses list comprehension, that is a new list object is generated between the square brackets and a reference to that object is assigned to mov_av_contact_idx.

List comprehension is very useful. Here's a simple example. This doubles every value in a list.

original = [10, 5, 20, 2, 8]
double = [num * 2 for num in original]

double_alt = []
for num in original:
    double_alt.append(num * 2)
    
print(original)
print(double)
print(double_alt)
Which will generate this output:
Output:
[10, 5, 20, 2, 8] [20, 10, 40, 4, 16] [20, 10, 40, 4, 16]
Notice I used list comprehension for double and then a standard for loop approach for double_alt, so you can compare and contrast. Most list comprehensions can be written in longer form.

The basic structure is:

[expression for variables in iterator]

You can have additional for loops on the end (inside the closing ] ), and if conditions.

Now you should be able to figure out what that last line actually does.
I am trying to help you, really, even if it doesn't always seem that way
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020