python中indexerror怎么解决,如何解决IndexError:使用Python中的内部循环数组解决列表分配索引超出范围...

本文介绍了一位初学者在使用Python创建文件名和路径数组时遇到的问题,即在while循环中尝试访问超出数组范围的元素。通过提供正确的`append`方法使用示例,解决了列表越界错误,最终实现了预期的文件路径生成。
摘要由CSDN通过智能技术生成

I'm new to python. I'm creating 2 arrays file_name(stores name of the files) and path(stores paths of files). Values of path array are assigned inside while loop. But I'm getting the error:

IndexError: list assignment index out of range in Python

I had already wasted several hours on this one, but haven't got the output as I expected. So, can you please let me know where I have made the mess? Any help will be highly appreciated. Thanks in advance.

My Code:

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']

path = []

count = 0

while count < 9:

path[count] = "D:\\Work\\"+file_name[count]+".csv"

print (path[count])

count = count + 1

Expected Output:

D:\\Work\\abc.csv

D:\\Work\\xyz.csv

D:\\Work\\pqr.csv

D:\\Work\\mno.csv

D:\\Work\\def.csv

D:\\Work\\ghi.csv

D:\\Work\\rst.csv

D:\\Work\\uvw.csv

D:\\Work\\jkl.csv

解决方案

You are looking for the append method.

file_name = ['abc','xyz','pqr','mno','def','ghi','rst','uvw','jkl']

path = []

count = 0

while count < 9:

path.append("D:\\Work\\"+file_name[count]+".csv")

print (path[count])

count = count + 1

You will get your expected output.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值