简体   繁体   中英

Can anyone help me explaining line 2 of this python program?

I am doing leedcode problem and I found this solution online. I haven't understood line 2 lookup = {x[0]: i for i, x in enumerate(pieces)} . Can anyone tell me how is it working? Also it will be cool if you can help me understanding whole program.

def canFormArray( arr, pieces):
    
    lookup = {x[0]: i for i, x in enumerate(pieces)}
    
    i = 0
    while i < len(arr): 
        if arr[i] not in lookup:
            return False
        for c in pieces[lookup[arr[i]]]:
            if i == len(arr) or arr[i] != c:
                return False
            i += 1
    return True 

       
arr = [15,88]
pieces = [[88],[15]]
p = canFormArray(arr,pieces)
print(p)

Google list comprehension .

lookup = {x[0]: i for i, x in enumerate(pieces)}

can be translated as

lookup = {} # init empty dict
for i, x in enumerate(pieces):
    lookup[x[0]] = i

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