Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-通过循环将多个数据插入多个数组_Python_Arrays_Loops_Csv - Fatal编程技术网

Python-通过循环将多个数据插入多个数组

Python-通过循环将多个数据插入多个数组,python,arrays,loops,csv,Python,Arrays,Loops,Csv,我目前有3个不同的csv文件和一些数据。我想将数据插入3个不同的数组。这是我目前正在编写的代码 arrayList = [] for index, url in enumerate(urls): with open('filename{}.csv'.format(index),'r') as f: for line in f: while line != '': arrayList[index].append(line) 我知道代码肯定不会起作用

我目前有3个不同的csv文件和一些数据。我想将数据插入3个不同的数组。这是我目前正在编写的代码

arrayList = []
for index, url in enumerate(urls):
with open('filename{}.csv'.format(index),'r') as f:
    for line in f:
        while line != '':
            arrayList[index].append(line)

我知道代码肯定不会起作用。有什么办法我可以做到吗?

试试这个。它生成一个包含三个列表的列表。顺便说一句,Python中没有像Java中那样的“ArrayList”。只有一个“列表”,其行为类似于Java ArrayList

arrayList = []
for index, url in enumerate(urls):
    with open('filename{}.csv'.format(index),'r') as f:
        temparr=[]
        for line in f:
            if line != '':
                temparr.append(line)
        arrayList.append(temparr)
使用CSV模块:

import csv
arrayList = []
for index, url in enumerate(urls):
    with open('filename{}.csv'.format(index), 'rb') as f:
        reader = csv.reader(f)
        arrayList.append([row for row in reader])

有一些很棒的库可以使CSV阅读更容易。你想手工做这个吗?这个问题对你有帮助吗<代码>行时!='':没有多大意义,我认为
如果行:
更好。此外,您正在尝试为原始列表编制索引,就好像它是嵌套的一样;不是。您将其定义为1年,我意识到,使用csv模块解决了这个问题,谢谢您@roganjoshI真的建议使用csv模块来实现这一点,您只需添加可能代表具有多列的行的文本。你甚至不需要创建内部列表,因为csv模块可以为你完成。我只是修改了@Ezhars的代码,但我同意csv模块会更好。也许我会发布另一个答案哇,谢谢,这两个都是我想要的@ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000