【问题标题】:Is there any way to store functions in variables and create lists of variable-housed functions?有什么方法可以将函数存储在变量中并创建包含变量的函数列表?
【发布时间】:2015-12-26 04:33:45
【问题描述】:

我是 Python 新手 - 用 PHP、javascript 编写过一些脚本,但我不是程序员(尽管我是一名技术作家,具有记录 API 等经验,因此非常广泛的“被动”编程知道如何)。:

  1. 在此处执行以下步骤:https://en.wikibooks.org/wiki/A_Beginner's_Python_Tutorial/Functions。具体看链接re:简单的计算器程序

  2. 想知道我是否可以通过以列表形式存储用于不同计算的所有组件来减少程序的冗余,然后通过使用用户的菜单选项来处理任何计算请求的非常简单、通用的方法列表中的索引。我假设以这种方式构造事物是一种很好的形式,但不知道!原始教程显然更具可读性,但意味着需要对每个小“if”块重复执行相同的错误检查......

无论如何,我不知道如何将实际计算存储为列表中的元素。那可能吗?据我所知……我设法封装并调用列表中的一些细节,但仍然必须为每个单独的计算执行一系列“if”语句。

(对不起,如果这些问题是基本的。。我进行了一堆搜索,但没有找到明确的文档:这里是你可以捕获的所有内容,但无法以列表形式捕获)所以 - 我的链接到代码的变体:

#simple calculator program
# Prompts for possible calculations

add = ["Add this: ", "to this: ", "+"]
subtract = ["Subtract this: ", "from this: ", "-"]
multiply = ["Multiply this: ", "by this: ", "*"]
divide = ["Divide this: ", "by this: ", "/"]

# List of possible calculations
calcPrompts = [add, subtract, multiply, divide]

def promptEntries(Arg):
    try:
        op1 = int(input(Arg[0]))
        op2 = int(input(Arg[1]))
        operator = (Arg[2])
        return op1, op2, operator
    except:
        print("Invalid entry. Please try again.")
choice = 0

#This variable tells the loop whether it should loop or not.
# 1 means loop. Anything else means don't loop.

loop = 1

while loop == 1:
    #Display the available options
    print ("\n\nCalculator options are:")
    print (" ")
    print ("1) Addition")
    print ("2) Subtraction")
    print ("3) Multiplication")
    print ("4) Division")
    print ("5) Quit calculator.py")
    print (" ")

    try:
        choice = int(input("Choose your option: "))
        choice = choice - 1
        op1, op2, operator = promptEntries(calcPrompts[choice])
        print(op1, operator, op2, "=", end=" ")
        if choice == 0:
            print(op1 + op2)
        elif choice == 1:
            print(op1 - op2)
        elif choice == 2:
            print(op1 * op2)
        elif choice == 3:
            if op2 != 0:
                print(op1 / op2)
            else:
                print("Division by zero is invalid, please try again.")
        elif choice == 4:
            loop = 0
            print ("Thank you for using calculator.py")
    except:
        print("invalid entry, please try again.")

【问题讨论】:

    标签: python list function


    【解决方案1】:

    在您的情况下,您可以将运算符用作函数,由operator 标准库模块提供。

    如您所见,您可以将此类函数分配给变量,例如将它们全部插入列表中

    import operator as op
    f = [op.add,
         op.sub,
         op.mul,
         op.div,
         op.pow,
         op.mod]
    

    那么循环就可以变成

    while True:
        #Display the available options
        print ("\n\nCalculator options are:")
        for i, fun in enumerate(f):
            print("{}) {}".format(i+1, fun.__name__))
        print ("{}) Quit calculator.py".format(len(f)))
    
        choice = int(input("Choose your option: ")) - 1
        if choice == len(f):
            print("Thank you for using calculator.py")
            break
        op1 = int(input("enter operand1: "))
        op2 = int(input("enter operand2: "))
    
        try:
            result = f[choice](op1, op2)
        except IndexError:
            print("invalid entry, please try again.")
        except ZeroDivisionError:
            print("Division by zero is invalid, please try again.")
    
        print('{} {} {} = {}'.format(op1, f[choice].__name__, op2, result))
    

    注意:该示例仅适用于二元函数。如果您想提供具有不同数量参数的函数组合,则需要进一步的工作。

    【讨论】:

    • 感谢您的代码,Pynchia。非常感谢最初的信息:导入 Operator .. module(?)... 以及因此创建列表的能力。除此之外......足够多的我还不熟悉的未注释代码。将尝试破译它们并找出菜单消失的地方! :-) 除其他外,聚合语法目前对我来说是陌生的:for i, fun in enumerate(f): print("{}) {}".format(i+1, fun.__name__))...但我很欣赏这个帖子——值得深思! :-)...很多东西要学
    • 不客气。请善待并接受答案和/或投票给你得到的答案
    • 嗨 Pynchia,让我先看看我是否可以在我的代码练习中制作一个或两个答案的组合,在这种情况下,我很乐意接受答案/赞成票。 (可能几天都没有时间。)晚安。
    • 使用您的代码 - 我发现了几个小错误 + cmets: "div" 导致错误 - 在操作员模块中有一个 "truediv",所以改用它。还将上面的 format(len(f))) 更改为 format(len(f)+1)),否则菜单项编号重复。下一个挑战是使界面更加“用户友好”。您的代码是高效的(并且值得赞赏!)-通过玩它,我学到了超出原始问题范围的东西。下一步是使提示和结果“用户友好”,因为您的代码从 op 模块中获取缩写的东西
    • 从上面继续 - 所以我会试验一下......例如,这是当前代码生成的 Calculator 选项是:1)添加 2)sub 3)mul 4)truediv 5)退出计算器.py 选择您的选项:1 输入操作数1:2 输入操作数2:2 2 添加2 = 4
    【解决方案2】:

    是的,在 python 中,函数是第一类对象,您可以像使用任何其他对象一样使用它们。例如,您可以让两个变量引用同一个对象:

    def myFunction():
        pass
    
    newVariable = myFunction
    print(newVariable is myFunction)
    

    或从列表或字典中引用函数:

    myList = [myFunction, 1, 2, 3]
    print(myList[0] is myFunction)
    myDict = {0:myFunction, 1:1}
    print(myDict[0] is myFunction)
    

    以上对于python的内置函数、标准库中的函数和你编写的函数都是正确的。例如:

    from operator import add
    
    def countZeros(a):
        return sum(item == 0 for item in a)
    
    listOfFunctions = [sum, add, countZeros]
    

    【讨论】:

    • 谢谢,毕里科。将使用您提供的内容,看看我是否可以提出新的和改进的代码位。
    猜你喜欢
    • 2020-06-17
    • 2015-12-17
    • 1970-01-01
    • 2019-01-24
    • 2019-05-31
    • 2017-02-25
    • 2017-02-27
    相关资源
    最近更新 更多