繁体   English   中英

"Python exec() NameError: name 'o' is not defined"

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM