gpt4 book ai didi

python - 替换为 "if"以根据参数在函数中执行不同的操作

转载 作者:行者123 更新时间:2023-12-01 05:23:58 26 4
gpt4 key购买 nike

我正在尝试根据传入的参数来更改函数的行为。我正在考虑使用 if 语句,但我真的不想这样做。示例:

def BigPrime(numP, plist = [], x = 1, counter =0):
while len(plist) <= numP:
if x == 1 or x == 2 or x == 5:
plist.append(x)
elif x % 2 is not 0 and int(str(x)[-1]) is not 5:
for div in plist[1:]:
#Non mettere niente qui, strane magie
#accadono in questo luogo...
if x % div == 0:
break
else:
plist.append(x)
counter += 1
x += 1
return plist, counter

编辑:好的,因为这个例子并没有说服很多人,我把真正的功能。对困惑感到抱歉!欢迎任何建议!

我需要这样的东西:

def foo(arg = 0, x = 0):
if not arg:
while True:
pass
else:
while x < arg:
print('bar')
x+=1

这看起来真的很糟糕,这真的是唯一的方法吗?难道没有更优雅的解决办法吗?

最佳答案

由于函数 foo 的行为在这两种情况下完全无关,因此我认为 if 没有任何问题。

既然您决定避免使用 if 语句,您可以定义两个函数并在它们之间选择您选择的任何其他方式:

def foo(arg = 0, x = 0):
def loop_forever():
while True:
pass
def print_stuff():
while x < 100:
print('bar')
x += 1
# now, any of these:

# if expression not if statement!
print_stuff() if arg else loop_forever()

# what people did before the if expression
# *but* you have to change print_stuff to return a true value
arg and print_stuff() or loop_forever()

# data-driven design, buzzword-compliant ;-)
[loop_forever, print_stuff][bool(arg)]()

通常,要为此选择一种技术,您需要查看两种情况之间的相同点和不同点,并在此基础上决定使用哪些抽象。但在这种情况下,两者之间没有任何相同之处。

这里有一种“丑陋的输入,丑陋的输出”原则:除了将两个不相关的操作分别写在两个不同的地方之外,基本上没有其他方法可以表达它们。如果您的代码中只有一个点负责,无论您将这些位置分隔为 if 的子句,还是作为两个不同的函数,或者作为两个具有多态性的不同类,都几乎无关紧要。定义它们、在它们之间进行选择并执行它们。如果这三件事在不同的地方完成,那么您将需要做出重大决定。

对于您的真实代码,这就是我认为我会写的内容,因为它是有值(value)的。我完全有可能引入了一个错误,但我不认为代码太多,以至于我需要编写更多的函数。我并不声称理解代码的用途,因为 3 是素数,但我相信以下内容是等效的:

def BigPrime(numP, plist = [], x = 1, counter =0):
while len(plist) <= numP:
if x in (1, 2, 5):
plist.append(x)
elif x % 2 != 0 and x % 5 != 0
if all(x % div != 0 for div in plist[1:]):
plist.append(x)
counter += 1
x += 1
return plist, counter

有一个可能的优化,即 plist[1:] 复制数组,因此 itertools.islice(plist, 1, None) 可能会更好。

关于python - 替换为 "if"以根据参数在函数中执行不同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21762026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com