如何在python中创建列表、添加值并将其取出

如何在python中创建列表、添加值并将其取出,python,csv,matrix,Python,Csv,Matrix,我是python新手。 我想从csv文件中读取数据,然后根据这些数据创建一个图形。 我有一个2列20行的csv文件。 在第一行我有1个,第二行有2个,依此类推,直到20。 我想取这个坐标,画一张图 这就是我到目前为止所做的: import csv from pylab import * with open('test.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|'

我是python新手。 我想从csv文件中读取数据,然后根据这些数据创建一个图形。 我有一个2列20行的csv文件。 在第一行我有1个,第二行有2个,依此类推,直到20。 我想取这个坐标,画一张图

这就是我到目前为止所做的:

import csv
from pylab import *

with open('test.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') # open the csv file
    for row in spamreader:
        print ', '.join(row) #  in each loop, row is getting the data,
                             # first row is [1,1] , then [2,2] and so on

plot()
show()
现在,我想的是把行放在最后,2列,20行,所有数据。 然后我需要做参数x,作为第一列,y作为第二列,并给出x,y的绘图

我的问题是我不知道如何保存行中的所有值,以及如何只取第一列和第二列


谢谢大家!

您可以使用它来获取X轴和Y轴:

with open('./test4.csv', 'rb') as csvfile:
    (X,Y) = zip(*[row.split() for row in csvfile])

您在读取csv文件时遇到问题
1) 分隔符=','

关于填充图形的x和y值。只需读取每行的第一个和第二个值,并填充x和y列表

这是修改后的代码:

import csv
from pylab import *

with open('test.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # open the csv file
    x = []
    y = []
    for row in spamreader:
        x.append(row[0])
        y.append(row[1])
        print ', '.join(row) #  in each loop, row is getting the data,
                         # first row is [1,1] , then [2,2] and so on

plot(x, y)
show()

您好,我正在这样做:从pylab import*导入csv,open('test.csv','rb')作为csvfile:(X,Y)=zip(*[row.split(),用于csvfile中的行])#spamreader=csv.reader(csvfile,delimiter='',quotechar='.#用于spamreader中的行:#print','。#join(row)plot()show(),但我得到一个错误:(X,Y)=zip(*[row.split()用于csvfile中的row])ValueError:需要多个值才能解压,这一定是因为数据的格式。只需打印此[row.split()用于csvfile中的row],然后让我知道您得到了什么?如果您的值用逗号分隔,则可以使用拆分(',')。实际上,Vikash的答案更优雅,为“zip”是这种计算的理想选择。使用“,”分隔行的更改将非常有效。但是,由于您是python新手,我想我的答案更容易理解。