gpt4 book ai didi

Python:如何在循环中从 `print` 调用 `eval`?

转载 作者:太空宇宙 更新时间:2023-11-03 12:12:23 24 4
gpt4 key购买 nike

当我从 eval 调用 print 时:

def printList(myList):
maxDigits = len(str(len(myList)))
Format = '0{0}d'.format(maxDigits)
for i in myList:
eval('print "#{0:' + Format + '}".format(i+1), myList[i]')

它给出了一个错误:

    print "#{0:01d}".format(i+1), myList[i]
^
SyntaxError: invalid syntax

我尝试使用 this ,并重写它:

def printList(myList):
maxDigits = len(str(len(myList)))
Format = '0{0}d'.format(maxDigits)
for i in myList:
obj = compile(src, '', 'exec')
eval('print "#{0:' + Format + '}".format(i+1), myList[i]')

但这会提示 i:

NameError: name 'i' is not defined

附言我正在处理 python2.6

最佳答案

你不能eval()一个print:eval()是用来计算表达式的,而print是一个语句。如果要执行语句,请使用 exec()。检查this question for a better explanation :

>>> exec('print "hello world"')
hello world

现在,如果你想让 exec 中的 i 可访问,你可以传递 locals() 变量:

>>> i = 1
>>> exec('print "hello world", i', locals())
hello world 1

另外,在你写的最后一个测试中,你在'exec'模式下编译(),这应该给你一个提示:)

关于Python:如何在循环中从 `print` 调用 `eval`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9330182/

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