试图将一个列表拆分为主列表中的多个列表 – Python

出于某种原因,我在尝试将逗号分隔的项目拆分为新列表然后将它们插入更高的列表时得到此回溯:

Traceback (most recent call last):
  File "S:/Personal Folders/Andy/Python Projects/People Cancelled/Analyze Customers Test.py", line 15, in <module>
    text[x] = textnew
TypeError: list indices must be integers, not str

这是我的代码:

from __future__ import division
from __future__ import print_function

in_file = open("s:/Personal Folders/Andy/Python Projects/People Cancelled/Analyze Authorize Truncated.csv")
text = in_file.readlines()
in_file.close()

header = text[0:1]
text = text[1:]

for x in text:
    textnew = x.split(",")
    text[x] = textnew

print(text)

正在使用的数据样本:

['3545869260,59.95,AUTH_CAPTURE,Jack,Franklin,810-555-2222,jack@francypants.com,01-Apr-2011 05:24:10 PM PDT\n', '354589999,0,VOID,Jacob,Rasnip,8224309464,goodness@finland.com,01-Apr-2011 05:24:10 PM PDT\n']

我基本上想把列表中的每个逗号分隔的信息放到一个单独的列表中,所以基本上在一个主列表中有一堆列表.

谢谢!

最佳答案 您在错误消息中获得了所需的信息:

TypeError: list indices must be integers, not str

你可能想做一些像:

the_new_list = [x.split(',') for x in text]

例:

>>> text = [
... '3545869260,59.95,AUTH_CAPTURE,Jack,Franklin,810-555-2222,jack@francypants.com,01-Apr-2011 05:24:10 PM PDT\n',
... '354589999,0,VOID,Jacob,Rasnip,8224309464,goodness@finland.com,01-Apr-2011 05:24:10 PM PDT\n']
>>> the_new_list = [x.split(',') for x in text]
>>> import pprint
>>> pprint.pprint(the_new_list)
[['3545869260',
  '59.95',
  'AUTH_CAPTURE',
  'Jack',
  'Franklin',
  '810-555-2222',
  'jack@francypants.com',
  '01-Apr-2011 05:24:10 PM PDT\n'],
 ['354589999',
  '0',
  'VOID',
  'Jacob',
  'Rasnip',
  '8224309464',
  'goodness@finland.com',
  '01-Apr-2011 05:24:10 PM PDT\n']]
>>>
点赞