简体   繁体   English

用 csv 读卡器读取数值数据

[英]Reading numerical data with csv reader

I am trying to read a csv table with csv reader, I want to rewrite the data into a tuple of tuples, where every subtuple contains the data of one row in the original file.我正在尝试使用 csv 读取器读取 csv 表,我想将数据重写为元组的元组,其中每个子元组都包含原始文件中一行的数据。 I am doing the following and it is working fine, but you can see how ugly it looks.我正在执行以下操作,并且工作正常,但是您可以看到它看起来有多丑。

table1 = tuple()
with open('data.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
        table1 = table1.__add__(tuple([tuple([float(row[0]), float(row[1])])]))  # giving that I know the data is arranged in two columns
print(table1)

The output looks good: output 看起来不错:

((0.0, 0.0), (0.0, 0.0), (0.00543154732031037, 4.2724591391866636e-05), (0.0347155846128363, 0.00021518683772895567), (0.1014894975795... etc

I am sure there is a better way to do this.我确信有更好的方法来做到这一点。 Please note that I can only use the builtin modules, this is why I didn't use Pandas.请注意,我只能使用内置模块,这就是我没有使用 Pandas 的原因。 Thank you for any suggestions.感谢您的任何建议。

Why not use a list of tuples - then you could use a list comprehension:为什么不使用元组列表 - 那么您可以使用列表推导:

with open('data.csv', newline='') as f:
    reader = csv.reader(f)
    table1 = [(float(row[0]), float(row[1])) for row in reader]

If you really need a tuple instead of a list: tuple() accepts iterables, so you can pass the list comprehension to it:如果你真的需要一个元组而不是一个列表: tuple()接受迭代,所以你可以将列表推导传递给它:

    table1 = tuple((float(row[0]), float(row[1])) for row in reader)

A list/tuple is suitable where you need repeated access/random access to all contained elements.列表/元组适用于您需要重复访问/随机访问所有包含的元素的情况。


An alternative would be a generator - suitable for all cases where you process the input in a "one-time-only, forward-only" fashion:另一种选择是生成器 - 适用于您以“一次性,仅前向”方式处理输入的所有情况:

def read_data(filename):
    with open(filename, newline='') as f:
        reader = csv.reader(f)
        for row in reader:
            yield (float(row[0]), float(row[1]))


for item in read_data('data.csv'):
    print(item)

Of course you could create a list from the generator as well:当然,您也可以从生成器创建一个列表:

table1 = [item for item in read_data('data.csv')]

# or

table1 = tuple(item for item in read_data('data.csv'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM