简体   繁体   中英

python: How to convert function to lambda expression?

I have the following function that converts a list into a dict.

def convert2Dict(item_list):
    d = {}
    for name in item_list:
       d.setdefault(name,0)
       d[name] += 1
    return (d)

When I pass a list like:

 takeOff_Airport = convert2Dict(takeOff_Airport)

I get a dict like:

{'LPPD': 4, 'DAAE': 1, 'EDDH': 16, ...... }

If I try to construct a map function like:

list(map(convert2Dict, takeOff_Airport))

I get:

[{'L': 1, 'P': 2, 'D': 1}, {'D': 1, 'A': 2, 'E': 1}, ....}

Which instead of iterating word by word is doing it character by character.

Any idea how to change it?

When you write

list(map(convert2Dict, takeOff_Airport))

you are essentially performing

result = []
for key in takeOff_Airpot:
    result.append(covert2Dict(key))

that is, you are applying the covert2Dict function to each key in the dictionary covert2Dict , and then collecting all of the results into a list.

If you want your function to operate on takeOff_Airport itself, simply pass it directly as an argument. You only need to use map or its relatives if you want to perform some action on each element on an iterable.

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