【发布时间】:2015-11-12 12:19:30
【问题描述】:
我正在开发一个程序,这个程序的意义是什么:
统计调查中包含的住户数量并以三栏格式打印。
计算家庭平均收入,并列出超过平均水平的每户家庭的识别号和收入。
确定收入低于 2015 年美国连续州贫困线的家庭百分比。使用给定的公式计算贫困水平的收入。该公式位于 povertycalc 函数中,该函数分配了名为 povertyLevel 的变量。
问题是这样的,我试图列出另一个低于贫困线的房屋列表的索引列表。
def main():
NumberofHouseholds = 0
inFile = open('program9.txt', 'r')
HouseIncome = []
global HouseIncome
avgincome = 0
lineRead = inFile.readline() # Read first record
while lineRead != '': # While there are more records
words = lineRead.split() # Split the records into substrings
acctNum = int(words[0]) # Convert first substring to integer
annualIncome = float(words[1]) # Convert second substring to float
members = int(words[2]) # Convert third substring to integer
global members
global annualIncome
print(acctNum, format(annualIncome, '.2f'), members, sep=' ')
HouseIncome.append(annualIncome)
povertycalc()
NumberofHouseholds = NumberofHouseholds + 1
avgincome = (avgincome+annualIncome)/NumberofHouseholds
lineRead = inFile.readline() # Read next record
# Close the file.
inFile.close() # Close file
print(avgincome)
print(HouseIncome)
def povertycalc():
indexKeep = []
global indexKeep
m = members
povertyLevel = 15930.00 + 4160.00 * (m-2)
if annualIncome < povertyLevel:
indexKeep.append(HouseIncome.index(HouseIncome[-1])) #Finds most recent index of household in HouseIncome and adds it to list indexKeep
print(indexKeep) #not printing the new value added to indexKeep
# Call the main function.
main()
昨天我给教授发邮件时,有人告诉我:
“您不能使用其他列表的数据作为索引。”
我应该怎么做才能提高效率?截至目前,该程序打印出所提供信息的三列(我将发布与该程序相关的 TXT 文件的链接)和一个空白括号,其中应该包含贫困线以下的房屋列表。
以下是与程序相关的文件中的文本:
1042 12180.06 3
1062 13240.45 2
1327 19800.56 2
1483 22458.23 7
1900 17000.09 3
2112 18125 4
2345 15623 2
3210 3200 1
3600 39500 5
3601 11970 2
4724 8900 3
6217 45000.70 2
9280 6200 1
1000 31000 3
1200 36000 2
5601 51970 9
5724 66900 3
5217 10002.68 2
5280 70000 1
5000 100000 6
5200 25000.4 3
5230 120000 6
6641 85000 7
7000 45500 4
7100 56500 3
8110 110005.9 8
9101 67590.40 6
【问题讨论】:
-
所以,我应该能够计算它是否在该线以下,如果是,我会怎么做?将该房子添加到列表中以便稍后打印?
-
您可以在不使用全局变量的情况下进行此操作.. 您应该这样做。不要使用全局变量。通过函数参数传递信息,您的问题应该得到解决。不要使用全局变量......请......
标签: python