如何在python中将行从文件读入多维数组(或列表数组) [英] How to read lines from a file into a multidimensional array (or an array of lists) in python
本文介绍了如何在python中将行从文件读入多维数组(或列表数组)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个格式与此类似的文件:
I have a file with a format similar to this:
a,3,4,2,1
3,2,1,a,2
我想读取文件并创建一个列表数组
I want to read the file and create an array of lists
以下列方式:
array[0] = ['a','3','4','2','1']
array[1] = ['3','2','1','a','2']
我该怎么做?
到目前为止,我一直坚持:
So far I am stuck with:
f = open('./urls-eu.csv', 'r')
for line in f:
arr = line.split(',')
print arr
我真的是python新手.
I am really new to python.
推荐答案
您快到了,您只需要执行以下操作即可:
you're almost there, you just need to do:
arr = [line.split(',') for line in open('./urls-eu.csv')]
它逐行迭代地处理文件,用逗号分隔每一行,并将结果列表累积到列表列表中.您可以取消打开模式('r'
),因为它是默认模式.
it iteratively process file line by line, splits each line by comma and accumulates resulting lists into a list of lists. you can drop opening mode ('r'
) since it's a default one.
这篇关于如何在python中将行从文件读入多维数组(或列表数组)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文