在Python中随时随地更改变量名称

时间:2013-12-03 00:55:50

标签: python

我需要帮助我的代码中的一小部分,我有点生疏。

这里很难解释,但基本上我需要在变量之间切换,具体取决于他们的种族等,因为我通读了每个记录

基本上我想重命名变量,因为不同的类别,年龄,职业,国家,种族等都有很多变量。

类似于:

#(NewRecord[3] will have details of race)
if NewRecord[3] = "black"
var1 += blackcounter
else if NewRecord[3] = "white"
var1 += whitecounter`

可能是:

for NewRecord[3] = "%s"
var1 += "%s"counter

???我该怎么做?

有条件的信息......:

我正在努力制定的计划是每年超过5万人的收入预测指标。

whiteCountUnder50
asianCountUnder50
indianCountUnder50
otherCountUnder50
blackCountUnder50

whiteCountOver50
asianCountOver50
indianCountOver50
otherCountOver50
blackCountOver50

#if white
overchance += (whiteCountOver50 / TotalPeopleOver)
underchance += (whiteCountUnder50 / TotalPeopleUnder)
print ("overchance: ", overchance)
print ("underchance: ", underchance)

#if black
overchance += (blackCountOver50 / TotalPeopleOver)
overchance += (blackCountUnder50 / TotalPeopleUnder)
print ("overchance: ", overchance)
print ("underchance: ", underchance)

#if asian
....

#if indian
....

等...

2 个答案:

答案 0 :(得分:2)

你可以使用词典。

container = {}
#inserting arbitrary amount of black people
container["black"] = 254
#inserting arbitrary amount of white people
container["white"] = getWhitePeople()
print(str(container["white"]))
#prints whatever getwhitePeople() returned
container.update(getPairNewCategory())
#getPairNewCategory() returns {nameOfTheCategoryStringOrHash:initialValueInt}
print(str(container[nameOfTheCategoryStringOrHash]))
#prints whatever was in initialValueInt

你要做的事情基本上是这个

counter = {}
for entry in NewRecord:
    if entry in counter:
        counter[entry] += 1
    else :
        counter[entry] = 1

然而,最蟒蛇的方法是:

 from collections import Counter
 c = Counter(NewRecord)
 c["BlackOver50"] = 123123 #whatever the number of BlackOver50 entries in NewRecord

答案 1 :(得分:0)

目前还不完全清楚你想做什么,但我认为你想要的是一本字典。以下是描述它们的链接:http://docs.python.org/2/tutorial/datastructures.html

您可以执行以下操作:

var1 += counter[NewRecord[3]]

希望有所帮助。