索引器错误:字符串索引超出范围:

2024-06-16 11:04:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用88行填充一个.txt文件,每行有两个字符,用空格隔开,将每行的第一个字符复制到list#1中,将每个列表的第二个字符复制到list#2中,然后用这两个列表填充字典。但是,当我试图将文件中的数据复制到列表中时,出现了一些问题。你能告诉我我什么地方做得不对吗?在

我总是在输入“column1[count]=readit[0]的那一行出现这样的错误:“IndexError:string index out out 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()

Tags: thein列表indexinitcount字符list
3条回答

您得到错误是因为column1 = []*filezise实际上并没有列出长度文件的列表。(如果您查看结果,您将看到column1只是一个空列表。)当您尝试访问column1[count]时,count > 0时,您将得到该错误,因为column1中没有索引大于0的内容。在

你不应该尝试初始化列表。相反,请迭代文件中的行并附加适当的字符:

column1=[]
column2=[]
for line in file('codes.txt'):
    column1.append(line[0])
    column2.append(line[2])

当你写作的时候

 for line in modo:
        filezise+=1  

您已经使用了该文件。 如果您想再次使用它,您需要先执行modo.seek(0)操作来倒带文件。在

如果不倒带文件,下面的行将返回一个空字符串,因为文件中没有任何内容。在

^{pr2}$

当然,没有必要把文件翻两遍。你可以只做一次,然后附加到你的列表中。在

^{3}$

试试这个

codebook =  dict([''.join(line.strip().split(' ')) for line in open('codes.txt').readlines()])

相关问题 更多 >