![](/img/trans.png)
[英]Python: weird “NameError: name … is not defined” in an 'exec' environment
[英]Python exec() NameError: name 'o' is not defined
此處的代碼塊旨在查找一個列表中出現的任何字母,如果找到,則將第二個列表中的值替換為相同的索引值。
iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'
def updateList(x, y):
global iWord
global cWord
global letter
bomb = f"iWord[{x}] = {y}"
exec(bomb)
print(iWord)
[updateList(x, y) for x, y in enumerate(cWord) if y == letter]
當您使用字符串格式時,它不包括字符串上的引號。 重寫格式化程序以使用 REPR 形式的字符串:
iWord = ['_', '_', '_', '_']
cWord = ['w', 'o', 'o', 'd']
letter = 'o'
def updateList(x, y):
global iWord
global cWord
global letter
bomb = f"iWord[{x!r}] = {y!r}"
exec(bomb)
print(iWord)
[updateList(x, y) for x, y in enumerate(cWord) if y == letter]
這段代碼在很多方面都是錯誤的。 我不知道目的是否是為了娛樂而使用exec
,但這實際上是不需要的。 此外,不推薦使用列表推導作為循環來執行沒有輸出的函數。
這是實現目標的pythonic方法。
定義一個新列表:
iWord = [b if b==letter else a for a,b in zip(iWord, cWord)]
就地修改列表:
for i,x in enumerate(cWord):
if x == letter:
iWord[i] = letter
輸出: ['_', 'o', 'o', '_']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.