2016-11-21 50 views
1

讓我編輯我的問題來澄清。下面是Python代碼:如何在python中創建一個stata本地宏?

decade_begin = 1970 

while decade_begin <= 1994: 
    for x in range(0, 10): 
     a= decade_begin + x 
    decade_begin = a+1 
    decade_end=a 

print "year_",decade_begin,"s" #start year 

最後一行的輸出是:

year_1980s 
year_1990s 

我希望能夠創建一個變量,使得:

year_1990s = [a] 

在Stata這很容易,使用本地宏'x'。但在Python中,我認爲混合字符串和int在變量名是不允許的。

forval i = 1979/1994 { 
whatever if year == `i' 
save year_`i'.dta, replace 
} 

有關如何在python中實現的任何想法?

+0

對於那些熟悉Python但不熟悉STATA的人,你能解釋一下'x'是什麼嗎?你的意思是像[格式文字](http://stackoverflow.com/documentation/python/1019/string-formatting/4021/format-literals#t=201611212058243848285)? –

+0

我認爲它在STATA被稱爲本地宏。我找到的最簡單的解釋是:https://www.ssc.wisc.edu/sscc/pubs/stata_prog1.htm – Carla

+0

它**被稱爲本地宏。這在源碼http://www.stata.com/help.cgi?foreach上是非常明確的但我懷疑Stata [NB]術語是否有助於回答python問題,這是一個如何遍歷列表的問題。 –

回答

1

喜歡的東西,這是一個大致相當於:

for x in ["apple", "banana", "orange"]: 
    with open(x + ".data", "w") as outfile: 
     outfile.write("whatever") 
0

如果我理解正確的話,你想創建使用字符串來命名變量變量名。 (相當於Stata中的本地宏在Python中稱爲變量)。您可以使用exec功能做到這一點:

>>> for i in range(1979, 1995): 
... exec("name_" + str(i) + " = " + str(i)) 

>>> print(name_1994) 
1994 

此代碼假設你使用Python 3,如果你使用的是Python 2,去掉外括號與execprint線。

然而,使用exec並不是解決Python中這個問題的最好方法(如解釋here)。如果您嘗試使用Python進行代碼編碼的方式與以前在Stata中進行編碼的方式相同,那麼稍後您可能會遇到問題。

更好的方法可能是創建一個字典併爲每個數字使用不同的密鑰。例如:

>>> names = {} 
>>> for i in range(1979, 1995): 
... names[i] = i 
>>> print(names) 
{1979: 1979, 1980: 1980, 1981: 1981, 1982: 1982, 1983: 1983, 1984: 1984, 1985: 1985, 1986: 1986, 1987: 1987, 1988: 1988, 1989: 1989, 1990: 1990, 1991: 1991, 1992: 1992, 1993: 1993, 1994: 1994}