def print_formatted(number):
for n in range(number):
n+=1
methods = ['int', 'oct', 'hex', 'bin']
ls = [eval(method + '(n)') for method in methods]
我不知道为什么eval()不能在list compreh中工作。
你的部分代码是完全正常的。 methods=['int','oct','hex','bin']ls=[eval(method+'n)')for methods in methods]
应按预期工作。
我不知道你为什么会出现名字错误。 如果您给我们完整的跟踪,我们可以帮助您调试,那将是最好的。
我看到的唯一错误是在for循环中有n+=1
。 您不需要递增n
,因为对于范围(数字)中的n:
已经递增了它。
它确实可以工作,但是eval不理解“(n)”
(n未解析)。 按以下方式尝试:
number = 5
def print_formatted(number):
for n in range(number):
# n+=1 <-- not necessary
methods = ['int', 'oct', 'hex', 'bin']
ls = [eval(method + '('+ str(n) + ')') for method in methods]
return ls
print(print_formatted(number))
产出:
[4, '0o4', '0x4', '0b100']