我不知道该怎么说,所以我直接举个例子
month1=31
month2=28
month3=31
month4=30
#number of days in certain months
monthnumber=3
# I want to find the number of days in the third month
monthnumberstr=str(monthnumber)
daysinmonth=("month"+monthnumberstr)
print(daysinmonth)现在我希望它能打印31,但是我得到了month3作为输出。如何使输出成为变量的变量。再说一遍,我不知道该怎么说。我只希望输出是31,而不是month3
发布于 2013-11-26 05:05:41
Asad的回答是好的
或
在你的情况下,你可以试试这个-:
monthnumberstr=str(monthnumber)
daysinmonth= eval("month"+monthnumberstr)你将在一个月内得到month3的价值
:)
发布于 2013-11-26 05:06:38
为了明确起见,您可以间接地访问Python中的变量。但是对于你想要做的事情来说,这是一个不太合适的解决方案,你应该像@Asad建议的那样使用适当的数据结构。
如果有人真的对如何间接访问变量感到好奇,您可以这样做:
print(locals()[daysinmonth])发布于 2013-11-26 05:07:16
在代码中,您将monthnumber you分配为monthnumber值的字符串表示形式,即“3”。因此,当您打印月份编号时,您将打印“3”。您可能需要使用一个列表,如下所示:
months = [31, 28, 31, 30]
monthnumber = 3
print(months[monthnumber])https://stackoverflow.com/questions/20208852
复制相似问题