简体   繁体   English

使用反向参数创建函数的 Python 代码

[英]Python code to create function with Reversed arguments

How to write a function that returns the reversed arguments of a previous function?如何编写一个返回前一个函数的反向参数的函数? The function can return an int, char, string, etc. Examples: f=pow(2,3)=8 (original) g=pow(3,2)=9 (reversed arguments)该函数可以返回 int、char、string 等。 示例:f=pow(2,3)=8(原始) g=pow(3,2)=9(反向参数)

capitalize_first_and_join first second third = FIRSTsecondthird (original) capitalize_first_and_join first second third = THIRDsecondfirst (reversed arguments) capitalize_first_and_join first second third = FIRSTsecondthird (original) capitalize_first_and_join first second third = THIRDsecondfirst(反向参数)

join_with coder best the are you = coder,best,the,are,you (original) join_with coder best the are you = you,are,the,best,coder (reversed arguments) join_with coder best the are you = coder,best,the,are,you (original) join_with coder best the are you = you,are,the,best,coder(反向参数)

The name of the function I need to create is reversed_args(f)我需要创建的函数名称是 reversed_args(f)

Regards,问候,

def reversed_args(f):
    # create the function here

    int_func_map = {
    'pow':pow,
    'cmp':cmp,
    }

    string_func_map ={
    'join with': lambda separator, *args: separator.join(*args),
    'capitalize_first_and_join': lambda first, *args: ''.join([first.upper()] + list(args)),
    }

    queries = int(raw_input())
    for _ in range (queries):
    line = raw_input().split()
    func_name, args = line[0], line[1:]
    if func_name in int_func_map:
        args = map(int, args)
        print reversed_args(int_func_map[func_name])(*args)
    else:
        print reversed_args(string_func_map[func_name](*args)




    f=pow(2,3)=8 (original)
    g=pow(3,2)=9 (reversed arguments)

    capitalize_first_and_join first second third = FIRSTsecondthird (original)
    capitalize_first_and_join first second third = THIRDsecondfirst (reversed arguments)

    join_with coder best the are you = coder,best,the,are,you (original)
    join_with coder best the are you = you,are,the,best,coder (reversed arguments)

this is code should help:这是代码应该有帮助:

from functools import wraps

def reversed_args(f):
    @wraps(f)
    def g(*args):
        return f(*args[::-1])
    return g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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