【发布时间】:2014-04-16 03:05:41
【问题描述】:
我正在尝试获取一个由 88 行填充的 .txt 文件,每行有两个由空格分隔的字符,将每行中的第一个字符复制到列表 #1,将每个列表的第二个字符复制到list #2 然后用这两个列表填充字典。但是,当我尝试将文件中的数据复制到我的列表中时,出现了问题。你能告诉我我做错了什么吗?
在我输入“column1[count] = readit[0]”的那一行,我不断收到这个错误:“IndexError: string index out of range”
def main():
modo = open('codes.txt', 'r') #opening file
filezise = 0 #init'ing counter
for line in modo:
filezise+=1 #counting lines in the file
column1 = []*filezise
column2 = []*filezise #making the lists as large as the file
count = 0 #init'ing next counter
while count < filezise+1:
readit = str(modo.readline())
column1[count] = readit[0] ##looping through the file and
column2[count] = readit[2] ##populating the first list with the
count+=1 #first character and the second list
print(column1, column2) #with the second character
index = 0
n = 0
codebook = {} #init'ing dictionary
for index, n in enumerate(column1): #looping through to bind the key
codebook[n] = column2[index] #to its concordant value
print(codebook)
main()
【问题讨论】:
-
readit 是一个字符串,而不是一个列表。
-
@Marichyasana,我想他知道这一点,但他仍然可以索引它。
标签: python list dictionary range