简体   繁体   English

我的元组怎么了?

[英]What is wrong with my tuple?

I created a function to take in a text file with such data: 我创建了一个函数来接收带有此类数据的文本文件:

2012-01-01  09:00   Angel   Men's Clothing  214.05  Amex
2012-01-01  09:00   Ben Women's Clothing    153.57  Visa
2012-01-01  09:00   Charlie Music   66.08   Cash

and it converts that into a list of tuples: 并将其转换为元组列表:

Code : myList = [tuple(j.split("\t")) for j in stringX.split("\n")]
Result:
[('2012-01-01', '09:00', 'Angel', "Men's Clothing", '214.05', 'Amex'), 
('2012-01-01', '09:00', 'Ben', "Women's Clothing", '153.57', 'Visa'), 
('2012-01-01', '09:00', 'Charlie', 'Music', '66.08', 'Cash')]

And further converts it into this: 并将其进一步转换为:

Code: nameList = [(float(item[4]),item[2])for item in myList]
Result: [(214.05, 'Angel'), (153.57, 'Ben'), (66.08, 'Charlie')]

With that small sized text file, its running perfectly. 使用该小型文本文件,它可以完美运行。 But I have to convert a big text file that is over 200 MB with over 1 million lines. 但是我必须转换一个超过200 MB,超过一百万行的大文本文件。 It manages to convert into list of tuples but it doesn't convert further into the smaller list of tuples as shown above. 它设法转换为元组列表,但没有进一步转换为较小的元组列表,如上所示。

It gives me the error when i run the program with the Big File: 当我使用大文件运行程序时,它给了我错误:

File "C:\Users\Charlie\Desktop\PYC\PYTHON ASSIGNMENT\test3.py", line 34, in <listcomp>
nameList = [(float(item[4]),item[2])for item in myList]
IndexError: tuple index out of range

You tuple has an empty entry that is why you are getting "IndexError: tuple index out of range" 您的元组有一个空条目,这就是为什么您得到“ IndexError:元组索引超出范围”的原因

You can add an if condition to validate if the tuple has any values in it. 您可以添加一个if条件来验证元组中是否包含任何值。

EX: 例如:

myList = [('2012-01-01', '09:00', 'Angel', "Men's Clothing", '214.05', 'Amex'), 
('2012-01-01', '09:00', 'Ben', "Women's Clothing", '153.57', 'Visa'),
(), 
('2012-01-01', '09:00', 'Charlie', 'Music', '66.08', 'Cash')]


nameList = [(float(item[4]),item[2])for item in myList if item]
print nameList
[(214.05, 'Angel'), (153.57, 'Ben'), (66.08, 'Charlie')]

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

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