如何使数据文件中的每一行成为元组列表中的元组? [英] How can I make each line in a data file a tuple in a list of tuples?

查看:127
本文介绍了如何使数据文件中的每一行成为元组列表中的元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为CustomerList.txt的文本文件,看起来像这样

I have a text file called CustomerList.txt and it looks like this

134998,Madison,Foxwell,825 John Street,Staunton,VA,24401,6655414998

最终结果应该是这样的

with open("CustomerList.txt", "r") as fin:
    ID, Firstname, Lastname, Address, City, State, Zip, Phone = zip(*[l.split() for l in fin.readlines()])

到目前为止,这就是我所拥有的,但是我收到一条错误消息,提示我需要3个以上的值才能正常使用.我昨天才刚开始使用元组,所以请对该新手保持尽可能简单的基础.如果您能解释一下为什么行得通,那就太好了!

That's what I have so far, but I get an error that says I need more than 3 values to upack. I just started using tuples yesterday so please keep things as basic as possible for this newbie. If you could include an explanation as to why it worked that would be great!

步骤1:数据文件中的每一行都应成为元组列表(或列表中的列表)中的元组.

Step 1: Each line in the data file should become a tuple in a list of tuples (or a list within a list). It would need to be before what I created in the last program which is this.

第2步: 在返回函数内部,我需要获取一个ID号(例如134998)来搜索匹配项,如果找到匹配项,则返回它作为元组/列表,如果不返回空的元组/列表,则将其作为元组/列表返回.它们可以是字符串,因为它们不是计算.

Step 2: Inside of the returning function I'll need to get a ID number (like 134998) to search for a match and if a match is found return it as a tuple/list if not return an empty tuple/list. They can be strings because they aren't calculations.

推荐答案

希望以下内容可以帮助您入门:

Hopefully, the below will get you started:

首先,默认情况下split()会按空格(即空白)分割,并且您希望它用逗号分割-因此请将其更改为:.split(',') ...

Firstly, by default split(), splits by whitespace (i.e. empty space) and you want it to split by a comma - so change it to: .split(',')...

此外,我运行rstrip()删除了换行符(\n).

Also, I ran rstrip() to remove the new_line character (\n).

此外,您想将标题压缩到每一行而不是全部数据.您当前的"for循环"在各行之间循环(每行将包含一个单独的数据条目),因此zip需要在其内部(对每条单独的行进行压缩),而不是在其外部(即,不对整个数据进行压缩).另外,我个人发现压缩数组比分配长列表变量更容易(我不确定这是否会实际工作).

Moreover, you want to zip the headers to each line and not the overall data. Your current 'for loop', loops over the lines (which would each contain a separate data entry), thus the zip needs to be inside it (zipping each individual line) and not outside it (i.e. not zipping the entire data). Also, I personally find it easier to zip an array rather than assigning a long list variables (I'm not sure if that would actually work).

这就是我从第一步开始的方式:

This is how I would start with the first step:

with open("positionfile.txt", "r") as fin:
    header = ['ID', 'Firstname', 'Lastname', 'Address', 'City', 'State', 'Zip', 'Phone']
    print [zip(header,l.rstrip().split(',')) for l in fin.readlines()]

这篇关于如何使数据文件中的每一行成为元组列表中的元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆