Python Forum
Explain a piece of code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Explain a piece of code
#1
Hi there,

Could someone please explain very clearly what the following piece of code is doing?

def question_set(X):
    qset = [[] for col in X[0]]
    for row in X:
        for i,col in enumerate(row):
            qset[i].append(col)
    
    return [set(row) for row in qset]

question_set(X_train)
I'm quite new to this, so I thank you greatly! Heart
Larz60+ write Nov-19-2020, 04:04 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Added tags for you this time. Please use bbcode tags on future posts.
Reply
#2
This function takes as an argument an object X which is a sequence of rows of some array-like structure. Here is what it does:
  1. It uses the first row X[0] to determine the number of columns of the array and it creates a sequence of empty lists, one for each column.
  2. For each row of X, it appends each element of the row to the list of the corresponding column.
  3. At the end, it transforms every such created column into a set instance, thus elimitating duplicate items and forgetting the order in which they appear in the column.
  4. It returns finally the sequence of sets, each of them containing a unique instance of every value found in the columns of the initial array-like structure.
IMHO, the whole function could be simplified into
def question_set(X):
    return [set(c) for c in zip(*X)]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Self Paced Web course - split ip and print each piece in binary and hex sumncguy 2 2,293 Dec-04-2019, 06:03 PM
Last Post: jefsummers
  Please explain how to alter text with python code? navneet 4 2,302 May-21-2019, 03:38 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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