本文介绍了小问:如何打印变量的名称,而不是它的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 毫无疑问,我忽略了一些显而易见的事情,但这里有: 让我们说我为var赋值,例如: myPlace =''就在这里'' myTime =''现在'' 现在让我们说要打印出来两个变量,以及它们的名字。 我可以很容易地做到这一点: print" myPlace =%s,myTime =%s" %(myPlace,myTime) 但这要求我提前知道变量的名称。如果 它们是动态分配的。我正在寻找的是一些方法( 称之为f()),允许我这样做: print"%s =%s,% s =%s %(f(myPlace),myPlace,f(myTime),myTime) 任何想法? repr()不会为我做,也不是``。 谢谢 斯图尔特在卡尔加里 No doubt I''ve overlooked something obvious, but here goes: Let''s say I assign a value to a var, e.g.:myPlace = ''right here''myTime = ''right now'' Now let''s say I want to print out the two vars, along with their names.I could easily do this:print "myPlace = %s, myTime = %s" % (myPlace, myTime) But that requires that I know in advance the name of the vars. What ifthey are assigned dynamically. What I''m looking for is some method (call it f() ) that allows me to do this:print "%s = %s, %s = %s" % (f(myPlace), myPlace, f(myTime), myTime) Any ideas? repr() doesn''t do it for me, nor ``. thanksStewart in Calgary 推荐答案 使用字典而不是自由浮动变量来存储数据。 Stewarts_data = {''myPlace'':''就在这里'', ''myTime'':'''现在''} for Stewarts_data.items()中的项目: 打印''%s =%s''%项目 (有可能更好方法 - 例如在Python 2.4中你可以在字典中使用sorted() - 但这可以解决这个想法,我希望.b $ b希望。) Best, Brian vdB Use a dictionary instead of free floating variables to store your data. Stewarts_data = { ''myPlace'' : ''right here'',''myTime'' : ''right now'' }for item in Stewarts_data.items():print ''%s = %s'' %item (There are likely even nicer ways -- for instance in Python 2.4 youcan use sorted() on the dictionary -- but this gets the idea across, Ihope.) Best, Brian vdB 尝试这样的事情: Try something like this: print_vars =< function print_vars at 0x401e0d84> __builtins__ =< module''__ builtin__' '(内置)> myTime =''现在'' myPlace =''这里'' __name__ = ''__main__'' __doc__ =无 print_vars = <function print_vars at 0x401e0d84>__builtins__ = <module ''__builtin__'' (built-in)>myTime = ''right now''myPlace = ''right here''__name__ = ''__main__''__doc__ = None 这篇关于小问:如何打印变量的名称,而不是它的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-18 21:48