gpt4 book ai didi

python - 有没有办法遍历给函数的每个变量并确定其类型?

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:24 24 4
gpt4 key购买 nike

所以我正在尝试编写一个接受多个参数的函数,例如 a,b,c,其中一些可能是长度为 X 的列表,而另一些可能是单个值,但这事先是未知的。

然后该函数应创建参数集 (a[i],b[i],c[i]),这些参数集将被传递到多处理池。如果给定一个变量的单个值,它只会对每个参数集重复。

现在,如果我想遍历每个变量,我可以为每个变量写一个 if 语句:

def foo(a, b, c):
if type(a) == int:
# make list of length needed
# Repeat for each variable

但在实践中,这很快就会变得困惑和冗长。我想知道是否有更简单的方法来遍历输入变量。

我希望有类似的东西

def foo(a, b, c):
for variable in foo.__variables__:
if type(variable) == int:
# Make list of length needed

编辑:附加信息

正如 Lauro Bravar 所指出的,可以通过将参数作为列表传递来解决上述问题。不幸的是,我试图解决的全部问题包括存在多个可选变量,所以这不起作用。所以我正在寻找更多的代码来解决这种情况:

def foo(a, b, c, d=None, e=None):
for variable in foo.__variables__:
if variable is not None:
if type(variable) == int:
# Make list of length needed

有没有办法不使用**kwarg 来做到这一点?理想情况下,我希望所有参数都在定义中可见,因为可读性很重要(这将被没有编码经验的学生使用)

最佳答案

你可以通过*args传递你的变量

def foo(*args):
for item in args:
print(type(item))

foo([3,4,5],4,"foo")

输出:

<type 'list'>
<type 'int'>
<type 'str'>

第一次编辑我的回答:

关于您在问题中的附加信息:*args 占用了您希望的任意多个参数。当遍历 *args 的所有元素并检查它们的类型时,您可以将结果存储在 dictionarylist 中以使其可访问:

def foo(*args):
mylist = list()
for item in args:
if type(item) == int:
mylist.append([item])
elif type(item) == list:
mylist.append(item)
return mylist

result = foo([3,4,5],4,"foo")

输出:

[[3, 4, 5], [4]]

第二次编辑我的回答:

在评论部分你添加了两个条件:

  1. help()函数需要返回foo的参数
  2. 您不能使用*args,因为您要创建指定参数的参数集(不支持开放式传递方案*args)

所以我的新方法处理内置函数 locals() ,返回“当前本地符号表”。当在函数内调用 locals() 时,它将返回函数的所有参数及其作为字典的值。确保在一开始就调用它,因为在运行时可能会在函数中创建新的局部变量,并且您可能会陷入循环。

这个怎么样?

def foo(a, b, c, d=None, e=None):
foo_arguments = locals()
for variable in foo_arguments:
if foo_arguments[variable] is not None:
if type(foo_arguments[variable]) == int:
print("Detected argument named {} which is an integer of value {:d}"
.format(variable, foo_arguments[variable]))

result = foo([3,4,5], 4, "foo", d=10)

这允许您为 abc 和可选的 de。与

print(help(foo))

返回

Detected argument named b which is an integer of value 4
Detected argument named d which is an integer of value 10
Help on function foo in module __main__:
foo(a, b, c, d=None, e=None)

关于python - 有没有办法遍历给函数的每个变量并确定其类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54177656/

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