简体   繁体   中英

Is there a way to call multiple functions inside one Python map function?

The project that I am currently working on requires me to convert RGB tuples to singular binary strings.

I am currently using output.append(''.join(map('{:0>8}'.format, map(str, map("{0:b}".format, each))))) to first convert each tuple element to binary, then to a string, and finally pad with zeroes before joining so it is still possible to tell each RGB element apart. It works perfectly, but I was wondering if there was a way to use only one map() instead of three?

Look at the documentation for the map method. You will see it takes a function and an iterable . You are not constrained to a specific method or way to define the method, so it could be a lambda or a reference to a builtin or custom method. So you can simply define a function to call whatever method you'd like, and pass it as the parameter.

def func(value):
    print(f"=== {value} ===")
    print("something else...")
    # any other function called you'd like

for i in map(func, [0, 1 , 2]):
    i

An you should see the output below:

=== 0 ===
something else...
=== 1 ===
something else...
=== 2 ===
something else...

Don't use map , prefer list comprehensions or generators.

output.append(''.join('{:0>8}'.format("{0:b}".format(item)) for item in each))

This looks overly complicated. Instead of

  • formatting a number as a binary string
  • then padding this string with zeros
  • then needlessly converting this string to a string again

just use {:08b} to format a number as a zero-padded 8-digit binary string in one go.

You do not need to (and can't) pass multiple functions to map .

''.join(map('{:08b}'.format, each))

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