[英]In Visual Studio Code, how do I load my python code to a read-print-eval loop?
[英]Python: how do I call `print` from `eval` in a loop?
當我從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
我試着利用這個 ,然后重寫它:
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
PS我正在處理python2.6
你不能eval()
print
: eval()
用於計算表達式,print是一個語句。 如果要執行語句,請使用exec()
。 請查看此問題以獲得更好的解釋 :
>>> exec('print "hello world"')
hello world
現在,如果要在exec中使i可訪問,則可以傳遞locals()變量:
>>> i = 1
>>> exec('print "hello world", i', locals())
hello world 1
另外,在你寫的最后一個測試中,你在'exec'模式下編譯()應該給你一個提示:)
你不需要eval:
def printList(myList):
maxDigits = len(str(len(myList)))
str_format = '#{0:0' + str(maxDigits) + '}'
for i, elem in enumerate(myList, 1):
print str_format.format(i), elem
或者,正如@SvenMarnach所說,你甚至可以將格式化參數放入一個格式調用中:
def printList(myList):
maxDigits = len(str(len(myList)))
for i, elem in enumerate(myList, 1):
print '#{1:0{0}} {2}'.format(maxDigits, i, elem)
保持代碼的同時縮短代碼並使其更容易理解:
def printList(myList):
# int(math.log10(len(myList))+1) would be the appropriate way to do that:
maxDigits = len(str(len(myList)))
for i in myList:
print "#{0:0{1}d}".format(i+1, maxDigits), myList[i]
簡單的觀點是這樣的。 與使用它分開構建格式。 避免使用eval()
。
format = "#{0:" + Format + "}"
print format.format(i+1), myList[i]
不要讓事情比他們需要的更難。 這是另一個版本,只需一步即可構建格式。
format = '#{{0:0{0}d}}'.format(maxDigits)
print format.format(i+1), myList[i]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.