读取CSV文件并将其插入到python中的二维列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24606650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reading CSV file and inserting it into 2d list in python
提问by pafpaf
I want to insert the data of CSV file (network data such as: time, IP address, port number) into 2D list in Python.
我想在 Python 中将 CSV 文件的数据(网络数据,例如:时间、IP 地址、端口号)插入到 2D 列表中。
Here is the code:
这是代码:
import csv
datafile = open('a.csv', 'r')
datareader = csv.reader(datafile, delimiter=';')
data = []
for row in datareader:
data.append(row)
print (data[1:4])
the result is:
结果是:
[['1', '6', '192.168.4.118', '1605', '', '115.85.145.5', '80', '', '60', '0.000000000', '0x0010', 'Jun 15, 2010 18:27:57.490835000', '0.000000000'],
['2', '6','115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.002365000', '0x0010', 'Jun 15, 2010 18:27:57.493200000', '0.002365000'],
['3', '6', '115.85.145.5', '80', '', '192.168.4.118', '1605', '', '1514', '0.003513000', '0x0018', 'Jun 15, 2010 18:27:57.496713000', '0.005878000']]
But it is just one dimension and I don't know how to create 2D array and insert each element into the array.
但它只是一维,我不知道如何创建二维数组并将每个元素插入到数组中。
Please suggest me what code should I use for this purpose. (I looked the previous hints in the website but none of them worked for me)
请建议我为此目的应该使用什么代码。(我在网站上查看了以前的提示,但没有一个对我有用)
采纳答案by Dennis Sakva
You already have list of lists, which is sort of 2D array and you can address it like one data[1][1], etc.
您已经有了列表列表,它是一种二维数组,您可以像使用 data[1][1] 等一样对其进行寻址。
回答by Jamie Cockburn
That is a 2D array!
那是一个二维数组!
Can index it like this:
可以像这样索引它:
data[row][value]
For example, do get the IP address of the second line in your CSV:
例如,获取 CSV 中第二行的 IP 地址:
data[1][2]
回答by Ashoka Lella
say your indicies for ip_address, time, port are
说你的 ip_address、时间、端口的索引是
ip_address = 2
time = 3
port = 11
print [[item[ip_address], item[time], item[port]] for item in data]
output
输出
[['192.168.4.118', '1605', 'Jun 15, 2010 18:27:57.490835000'],
['115.85.145.5', '80', 'Jun 15, 2010 18:27:57.493200000'],
['115.85.145.5', '80', 'Jun 15, 2010 18:27:57.496713000']]
you can do this when appending rows into data
itself
您可以在将行附加到data
自身时执行此操作
for row in data reader:
data.append([row[ip_address], row[time], row[port]])
回答by Karim Tabet
Here's a clean way to get a 2D array from a CSV that works with older Python versions too:
这是一种从 CSV 获取二维数组的干净方法,也适用于较旧的 Python 版本:
import csv
data = list(csv.reader(open(datafile)))
print(data[1][4])