有没有一种Pythonic方法可以跳过for循环中的if语句以使代码运行更快?

2024-04-28 12:25:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个脚本,基本上是掷骰子,并检查掷骰子是否超过一个数x。我想重复这个过程n次,得到模具辊超过这个数x的概率。e、 g

Count = 0
for _ in itertools.repeat(None, Iterations):
    x = 3
    die_roll = rnd.randint(1,6)
    if die_roll > x:
        Count += 1
Probability_of_exceed = Count / Iterations

我想根据用户输入修改die roll和x。此用户输入将选择不同的例程来修改脚本,例如"Andy's_Routine"可能会将x更改为4。目前,我在for循环中使用if语句来检查哪些例程是活动的,然后应用它们

Count = 0
for _ in itertools.repeat(None, Iterations):
    x = 3

    if "Andy's_Routine" in Active_Routines:
        x = 4

    die_roll = rnd.randint(1,6)
    if "Bill's_Routine" in Active_Routines:
        die_roll += 1 
    if "Chloe's_Routine" in Active_Routines:
        # do something
        pass

    if "Person_10^5's_Routine" in Active_Routines:
        # do something else
        pass

    if die_roll > x:
        Count += 1
Probability_of_exceed = Count / Iterations

在实践中,例程并不是简单到可以泛化,例如,它们可能会添加额外的输出。这些例程可以同时实现。问题是可能有成千上万个不同的例程,这样每个循环将花费大部分时间检查if语句,从而减慢程序的速度。你知道吗

有没有更好的方法来构造代码,检查哪些例程只使用一次,然后以某种方式修改迭代?你知道吗


Tags: in脚本noneforifcount例程active
1条回答
网友
1楼 · 发布于 2024-04-28 12:25:01

你在这里要求两件事-你希望你的代码更像python,你希望它运行得更快。你知道吗

第一个更容易回答:使Active_Routines成为函数列表而不是字符串列表,并从列表中调用函数。由于这些函数可能需要更改本地状态(xdie_roll),因此需要将状态作为参数传递给它们,并让它们返回新状态。重构可能如下所示:

def Andy(x, die_roll):
    return (4, die_roll)

def Bill(x, die_roll):
    return (x, die_roll + 1)

def Chloe(x, die_roll):
    # do something
    return (x, die_roll)

Active_Routines = [Andy, Bill, Chloe]

Count = 0
for i in range(Iterations):
    x = 3
    die_roll = rnd.randint(1,6)

    for routine in Active_Routines:
        x, die_roll = routine(x, die_roll)

    if die_roll > x:
        Count += 1

Probability_of_exceed = Count / Iterations

第二个更难回答。这种重构现在进行了大量函数调用,而不是检查if条件;因此missed branch predictions可能更少,但function call overhead更多。您必须对它进行基准测试(例如,使用timeit library)才能确定。但是,至少这段代码应该更易于维护。你知道吗

相关问题 更多 >