如果我不完全知道它的名字,我该如何打印变量?

例如,如果我有类似这样的代码:


x1 = 1

x2 = 2

x3 = 3


for i in range(3):

  #How do i get "x" + i and print the variable's value?

  print()


慕神8447489
浏览 131回答 3
3回答

神不在的星期二

如果要在不使用数组的情况下遍历编号变量,可以使用locals():x1 = 1x2 = 2x3 = 3for i in range(1,4): # Note that it's range(1,4) if you want 1, 2, 3  print(locals()[f"x{i}"])输出:123

互换的青春

关于你在这里问什么的信息不是很多,但我认为下面解决了它x1 = 1x2 = 2x3 = 3    lst = [x1,x2,x3]for i in lst:  print(i)输出:123

函数式编程

你可以使用eval函数来做到这一点:x1, x2, x3 = 1, 2, 3for i in range(1,4):  print(eval("x"+str(i)))输出:% python3 script.py123
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python