【发布时间】:2021-03-17 09:26:57
【问题描述】:
我这里有从文件读取的代码,应该创建和打印一个地区列表,以及有多少地区。
def main():
#open the file
myFile = open("Data.txt")
#read the first line
firstLine = myFile.readline()
#initialize a counter
count = 0
#for each line in the file
for dataLine in myFile:
#strip the end of the line
dataLine = dataLine.rstrip("\n")
#split the line into a list
dataList = dataLine.split(",")
#create a new list
districts = []
#if dataList[3] is not in districts already
if dataList[3] in districts == False:
#append dataList[3] to the districts list
districts.append(dataList[3])
count = count + 1
#print the districts list as well as how many were found
print("Here is a list of all districts:")
print(" ")
print(districts)
print("There are",count,"districts.")
#close the file
myFile.close
main()
但是,我遇到了一个问题,似乎没有从 dataList 将任何内容添加到地区列表中。我确信这与我的代码措辞方式有关,但我不清楚它可能是什么。任何帮助将不胜感激。
【问题讨论】:
-
注意
rstrip("\n")的使用可以替换为strip(),因为它默认会删除换行符
标签: python list for-loop append