Home > Blockchain >  the for loop within a list?
the for loop within a list?

Time:09-06

I'm still a beginner at learning Python. I want to ask something about loops. I found a written code like this:

user_ids = [u for u, c in user_ids_count.most_common(n)]
movie_ids = [m for m, c in movie_ids_count.most_common(m)]

how to read this code? I know that user_ids is the object and user_ids_count.most_common() is the function/method (please correct me if I'm wrong), but I have no idea what the logic sense of u for u, c and what does that mean because I can't find any loops example that's written like this.

CodePudding user response:

You are right. The user_ids_count.most_common() is the function/method. But the user_ids is a variable that stores the address for a list that you are creating.

The user_ids_count.most_common() method returns a list of tuples which means each element in that list consists of two values. With u for u, c in, you make an iteration on the list elements, in each iteration assign the first value in the tuple to u, and the second value in the tuple to c. Then you build a new array with u values.

Here is an example:

[u for u, c in [(1, 2), (3, 4), (5, 6)]]

will return:

[1, 3, 5]
  • Related