簡體   English   中英

使用反向參數創建函數的 Python 代碼

[英]Python code to create function with 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(反向參數)

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_args(f)

問候,

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)

這是代碼應該有幫助:

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