【问题标题】:Assigning and Calling built-in functions from a dictionary (Python)从字典中分配和调用内置函数 (Python)
【发布时间】:2026-01-07 21:25:05
【问题描述】:

每个人。我正在尝试解决如下编码挑战:

  1. 从用户那里得到一个字符串。之后,询问用户“你想对字符串做什么?”,允许用户选择下一个功能: "upper" - 使所有字符串大写 "lower" - 使所有字符串小写 " "spaces2newline" - 将所有空格重新换行 ... 打印结果 *使用字典“包装”该菜单

所以,我从中得到的是我需要制作一个字典,我可以从中调用命令并将它们分配给字符串。

显然,这是行不通的:

commands = {"1" : .upper(), "2" : .lower(), "3" : .replace(" ",\n)}

user_string = input("Enter a string: ")
options = input("How would you like to alter your string? (Choose one of the following:)\n
\t1. Make all characters capital\n
\t2. Make all characters lowercase")
#other options as input 3, 4, etc...

但也许有人可以推荐一种方法来实现这个想法?

我的主要问题是:

  1. 您能否以某种方式将内置函数分配给变量、列表或字典?
  2. 如何从字典中调用这样的函数并将它们作为命令添加到字符串的末尾?

感谢您的帮助!

【问题讨论】:

  • 天真的方式类似于{"1": lambda x: x.upper(), "2": lambda x: x.lower(), "3": lambda x: x.replace(" ", "\n")}

标签: python dictionary built-in


【解决方案1】:

使用operator.methodcaller

from operator import methodcaller


commands = {"1": methodcaller('upper'),
            "2": methodcaller('lower'),
            "3": methodcaller('replace', " ", "\n")}

user_string = input("Enter a string: ")
option = input("How would you like to alter your string? (Choose one of the following:)\
\t1. Make all characters capital\
\t2. Make all characters lowercase")

result = commands[option](user_string)

文档显示了一个纯 Python 实现,但使用 methodcaller 的效率略高。

【讨论】:

  • 谢谢!!!!我马上试试这个
  • 效果非常好,再次感谢您,传奇!
【解决方案2】:

好吧,chepner 的答案肯定要好得多,但是您可以解决此问题的一种方法是直接访问 String 类的方法,如下所示:

commands = {"1" : str.upper, "2" : str.lower, "3" : lambda string: str.replace(string, " ", "\n")}  # use a lambda here to pass extra parameters

user_string = input("Enter a string: ")
option = input("How would you like to alter your string? (Choose one of the following:)\
\t1. Make all characters capital\
\t2. Make all characters lowercase")

new_string = commands[option](user_string)

通过这样做,您将实际方法本身保存到字典中(通过排除括号),因此可以从其他地方调用它们。

【讨论】:

    【解决方案3】:

    也许你可以这样做:

    command = lambda a:{"1" : a.upper(), "2" : a.lower(), "3" : a.replace(" ",'\n')}
    
    user_string = input("Enter a string: ")
    options = input("How would you like to alter your string? (Choose one of the following:)")
    print("output:",command(user_string)[options])
    #\t1. Make all characters capital\n
    

    【讨论】:

    • 您不应该使用lambda 来分配名称。