简体   繁体   English

从csv文件创建元组列表

[英]create a list of tuples from csv file

I am python beginner struggling to create and save a list containing tuples from csv file in python. 我是python初学者在python中创建并保存包含来自csv文件的元组的列表。

The code I got for now is: 我现在得到的代码是:

def load_file(filename):
    fp = open(filename, 'Ur')
    data_list = []
    for line in fp:
        data_list.append(line.strip().split(','))
    fp.close()
    return data_list

and then I would like to save the file 然后我想保存文件

def save_file(filename, data_list):
    fp = open(filename, 'w')
    for line in data_list:
        fp.write(','.join(line) + '\n')
    fp.close()

Unfortunately, my code returns a list of lists, not a list of tuples... Is there a way to create one list containing multiple tuples without using csv module? 不幸的是,我的代码返回一个列表列表,而不是一个元组列表......有没有办法在不使用csv模块的情况下创建一个包含多个元组的列表?

split returns a list, if you want a tuple, convert it to a tuple: split返回一个列表,如果你想要一个元组,将它转换为一个元组:

    data_list.append(tuple(line.strip().split(',')))

Please use the csv module. 请使用csv模块。

First question: why is a list of lists bad? 第一个问题:为什么列表清单不好? In the sense of "duck-typing", this should be fine, so maybe you think about it again. 在“鸭子打字”的意义上,这应该是好的,所以也许你再想一想。

If you really need a list of tuples - only small changes are needed. 如果你真的需要一个元组列表 - 只需要进行小的更改。

Change the line 改变线

        data_list.append(line.strip().split(','))

to

        data_list.append(tuple(line.strip().split(',')))

That's it. 而已。

If you ever want to get rid of custom code (less code is better code), you could stick to the csv -module. 如果您想要摆脱自定义代码(代码更少代码更好),您可以坚持使用csv -module。 I'd strongly recommend using as many library methods as possible. 我强烈建议尽可能多地使用库方法。

To show-off some advanced Python features: your load_file -method could also look like: 要展示一些高级Python功能: load_file -method也可能如下所示:

def load_file(filename):
    with open(filename, 'Ur') as fp:
        data_list = [tuple(line.strip().split(",") for line in fp]

I use a list comprehension here, it's very concise and easy to understand. 我在这里使用列表理解,它非常简洁易懂。

Additionally, I use the with -statement, which will close your file pointer, even if an exception occurred within your code. 另外,我使用with -statement,它会关闭你的文件指针,即使你的代码中发生了异常。 Please always use with when working with external resources, like files. 请始终使用with外部资源的工作时,像文件。

Just wrap "tuple()" around the line.strip().split(',') and you'll get a list of tuples. 只需在line.strip().split(',')周围包装“tuple()”,你就会得到一个元组列表。 You can see it in action in this runnable gist . 你可以在这个可运行的要点中看到它的实际效果。

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

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