简体   繁体   中英

What does {..}[..] mean?

from functools import reduce
def str2int(s):
    def fn(x, y):
        return x * 10 + y
    def char2num(s):
        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
return reduce(fn, map(char2num, s))

I'm learning the function map() and reduce(). what does {...}[.] mean?

it's simply mean : build a dictionnary and return a specific value from a key.

print({'foo': 0, 'bar': 1}['foo']) # output : 0
print({'foo': 0, 'bar': 1}['bar']) # output : 1

Function char2num change a string to its int value. For example if:

s = '0' 

It returns:

0 #int

Actually the function find dictionary[s] (with key s ) and returns its value that is its int value.

{}[] means that check the dictionary for a particular key so if that key is found return it, consider this

str2int = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7':7, '8': 8, '9': 9}
get_3 = str2int['3']
print(get_3)

>>> 3

it's basically the same as assigning the dictionary to an identifer/variable and accessing the key if you try this

get_3 = str2int['10']

You get a KeyError that that particular key dosen't exist in the dictionary

as for the function in general mapping in general is used to apply a the operation of a function to an iterable

map(aFunction, aSequence)

remember strings in python are iterables, so the mapping returns the corresponding dictionary value

Reduce works by applying a function to an iterable till it returns a single value (ie reduce this list or iterable to a single value) for example

so for example if you call your function with the string

str2int('234')

The mapping goes through and maps the string to it's values in the dictionary and returns a list

[2, 3, 4]

after that the reduce takes the first two arguments as x and y and applies what operation x * 10 + y and calls it till it's just one value so on the first call

2 * 10 + 3 = [23, 4]

second call

23 * 10 + 4 = [234]

so we now have one value, finally the value 234 is returned at the end of the function you can play with the internal logic of the function to get used to the concept

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