gpt4 book ai didi

python - eval(dir()[0]) 在 python 中做什么

转载 作者:太空宇宙 更新时间:2023-11-04 09:40:06 25 4
gpt4 key购买 nike

我在 python 中遇到了一个程序的解决方案,但即使在搜索之后我也无法理解它的作用。谁能解释一下这条语句的作用。

a, b, c = map(numpy.array,eval(dir()[0]))

最佳答案

函数dir ,当不带参数调用时返回所有局部变量的名称,类似于 locals().keys()

def f(y):
print(dir()) # prints ['y']

然后,很明显,dir()[0] 是第一个局部变量的名称,eval(dir()[0]) 计算变量名称,即返回第一个局部变量的值。

def f(y):
print(dir()) # prints ['y']
print(dir()[0]) # prints 'y'
print(eval(dir()[0])) # prints the value of y

例如:

>>> f(77)
['y']
y
77
>>> f([1,2,3])
['y']
y
[1, 2, 3]

函数map使用第二个参数(必须是可迭代的)中的每个值调用第一个参数(必须是可调用的),并生成结果,例如

>>> for result in map(str.upper, ['foo', 'bar', 'baz']):
... print(result)
...
FOO
BAR
BAZ

将它们组合在一起,并假设第一个局部变量是一个名为 first_variable 的列表,则此代码:

a, b, c = map(numpy.array,eval(dir()[0]))

将与此代码相同:

a, b, c = first_variable
a = numpy.array(a)
b = numpy.array(b)
c = numpy.array(c)

关于python - eval(dir()[0]) 在 python 中做什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52046446/

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