Python:根据for循环中的条件选择功能?

发布于 2025-02-09 18:00:57 字数 643 浏览 1 评论 0原文

抱歉,如果标题有些模糊。我将在这里更详细地解释一切。假设我有此代码:

def function1(k):
    return k * 2


def function2(k):
    return k ** 2


func = 'Square'

for i in range(1, 10):
    if func == 'Multiply':
        function1(i)
    elif func == 'Square':
        function2(i)

如何修改上面的代码,以便IF语句可以在循环外面进行?似乎没有必要检查每个迭代的func的值,因为它不会在内部发生变化。循环。我正在寻找的是这样的东西:

def function1(k):
    return k * 2


def function2(k):
    return k ** 2


func = 'Square'

if func == 'Multiply':
     f = function1()
elif func == 'Square':
     f = function2()

for i in range(1, 10):
    f(i)

如果某事还不够清楚,或者我要问的是不可能的。

Sorry if the title is a little vague. I'll explain everything in greater detail here. So let's say I have this code:

def function1(k):
    return k * 2


def function2(k):
    return k ** 2


func = 'Square'

for i in range(1, 10):
    if func == 'Multiply':
        function1(i)
    elif func == 'Square':
        function2(i)

How can I modify the code above so that the if statement can go outside the loop? It seems unnecessary to check in every iteration the value of func since it's not going to change inside. the loop. What I'm looking for is something like this:

def function1(k):
    return k * 2


def function2(k):
    return k ** 2


func = 'Square'

if func == 'Multiply':
     f = function1()
elif func == 'Square':
     f = function2()

for i in range(1, 10):
    f(i)

Let me know if something isn't clear enough or if what I'm asking isn't possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

孤寂小茶 2025-02-16 18:00:57

将功能存储在dict中,然后您可以跳过语句。

def function1(k):
    return k * 2

def function2(k):
    return k ** 2

d = {"Multiply": function1, "Square": function2}

func = "Square"
f = d[func]
f(3)
# 9

Store the function in a dict, then you can skip the if statements.

def function1(k):
    return k * 2

def function2(k):
    return k ** 2

d = {"Multiply": function1, "Square": function2}

func = "Square"
f = d[func]
f(3)
# 9
梦里泪两行 2025-02-16 18:00:57

您可以执行此操作:

funcs = {'Multiply':function1, 'Square':function2}
theFunc = funcs[func]
for i in range(1, 10):
    x = theFunc(i)
    print(x)

传递中的一个注:^操作员没有采用参数的正方形,而是在其上执行位XOR。

You can do this:

funcs = {'Multiply':function1, 'Square':function2}
theFunc = funcs[func]
for i in range(1, 10):
    x = theFunc(i)
    print(x)

One note in passing: the ^ operator is not taking the square of the argument, but rather performing bitwise xor on it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文