加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:20:28 所属栏目: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]
出于某种原因,我在尝试将逗号分隔的项目拆分为新列表然后将它们插入更高的列表时得到此回溯:

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 PDTn','354589999,VOID,Jacob,Rasnip,8224309464,goodness@finland.com,01-Apr-2011 05:24:10 PM PDTn']

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

谢谢!

解决方法

您在错误消息中获得了所需的信息:

TypeError: list indices must be integers,not str

你可能想做一些像:

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

例:

>>> text = [
... '3545869260,... '354589999,01-Apr-2011 05:24:10 PM PDTn']
>>> 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 PDTn'],['354589999','0','VOID','Jacob','Rasnip','8224309464','goodness@finland.com','01-Apr-2011 05:24:10 PM PDTn']]
>>>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读