简体   繁体   中英

Python - construct set with for loop

Saw this code on leetcode and don't get what it does or how it works. Paths is a list of lists.

def solution(paths):
    s = set(p[0] for p in paths)    

Ok not sure which part of the code you were referring to.

def solution(**paths**):          #1
    s = set(p[0] for p in paths)  #2

#1 creates a function called solution, that takes one argument (path)

#2 assigns a set to the variable s .

set( ) is a function creates a set object.

p[0] is the item you want from the forloop. and you are grabbing the first variable in each set that is in path

it can also be interpeted as:

def solution(paths):
    s = {}           # declare variable
    for item in path: # use forloop
        s.add(item[0]) #add the first element of each item in path (the set in path)
    print(s)

test_path = [ ['a','b','c'] , ['a','e','f'], ['g','h','i'] ]
solution(test_path)

notice in the results printed below that only one of the 'a' is added because a set only has unique variables

>>>{'g', 'a'}

You can do some Research on list comprehensions. I only started learning Python a few months ago myself. but i found this great video that I think explains the different types of comprehensions very well.

Python Tutorial: Comprehensions

p is a list, and p[0] takes the first item in the sub-list, and this gets added to a set (ie, duplicates are removed).

For example, if paths = [[1,2,3] , [1,3,4], [2,3,4]]

s = {1, 2} 

Note that function doesn't return anything since it does not have 'return'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM