首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用python和TypeError解析特定值:列表索引必须是整数或切片,而不是字符串

使用python和TypeError解析特定值:列表索引必须是整数或切片,而不是字符串
EN

Stack Overflow用户
提问于 2018-06-17 01:42:59
回答 2查看 262关注 0票数 0

我被这个任务卡住了,而且我似乎无法破解代码。我的目的是解析文本,包含格式如下的行:

代码语言:javascript
复制
date time number

我想用它做一些简单的统计。

棘手的事情是创建一个系统,它将创建一个在任何给定日期只具有最高“编号”的int列表。

例如,给定以下内容:

followerNum.txt

代码语言:javascript
复制
2018-06-11 12:29 692
2018-06-11 12:55 690
2018-06-11 13:00 690
2018-06-11 14:40 690
2018-06-11 15:01 690 <-- this one
2018-06-12 06:00 687
2018-06-12 09:27 688
2018-06-12 09:30 688
2018-06-12 09:37 688
2018-06-12 09:48 688
2018-06-12 10:08 688 <-- this one
2018-06-13 06:00 699
2018-06-13 08:06 700
2018-06-13 10:34 702
2018-06-13 10:40 702 <-- this one
2018-06-14 06:00 709 <-- this one
2018-06-15 06:57 719 <-- this one
2018-06-16 07:50 721 <-- this one

因此,在本例中,列表将包含690, 688, 702, 709, 719, 721

我已经在这个问题上来回折腾了一段时间,现在我就是没有选择。此外,我希望每次代码运行时,它都会使用文件中的当前数据生成新的列表,并且我似乎能够为它创建一个循环。

这就是我得到的结果:

代码语言:javascript
复制
#open the file and create a list with the lines:

file = open("followerNum.txt").read().splitlines()

#get the first and last 'words' of the first line

date,b,folnum= file[0].split(" ")

#get the first and last 'words' of the second line

date2,b,folnum2 = file[1].split(" ")
#check if it worked
print(date, date2)

for i in file:

  if date2 == date:   #If both are equal, then replace it 
    folnum= file[i].split(" ",-1)
  else:               if not, append 
    folnum.append(file[i].split(" ",-1))

当我运行它时,我得到:

代码语言:javascript
复制
folnum= file[i].split(" ",-1)
TypeError: list indices must be integers or slices, not str

好吧,我希望你能看到noob在这里失败了,你会怎么做呢?看起来很酷,因为我是一个自学的新手:)

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50890242

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档