如何解决IndexError:使用Python中的内部循环数组列出分配索引超出范围 [英] How to resolve IndexError: list assignment index out of range using array inside loop in Python

查看:268
本文介绍了如何解决IndexError:使用Python中的内部循环数组列出分配索引超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手.我正在创建2个数组file_name(存储文件名)和path(存储文件路径). path数组的值在while循环内分配.但是我得到了错误:

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:列表分配索引超出了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.

我的代码:

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

预期输出:

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

推荐答案

您正在寻找append方法.

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

您将获得预期的输出.

这篇关于如何解决IndexError:使用Python中的内部循环数组列出分配索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆