python - 使用 python 和 TypeError 解析特定值:列表索引必须是整数或切片,而不是 str
问题描述
我被这个任务困住了,我似乎无法破解密码。我的意图是解析文本,包含格式如下的行:
date time number
我想用它做一些简单的统计。
棘手的事情是创建一个系统,该系统将int
在任何给定日期创建一个只有最高“数字”的 s 列表。
即给出以下内容:
追随者人数.txt
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
.
我已经来回考虑了一段时间,现在我只是没有选择。另外,我希望每次代码运行时,它都会使用文件中的当前数据创建新列表,并且我似乎能够为它创建一个循环。
这是我已经走了多远:
#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))
当我运行它时,我得到:
folnum= file[i].split(" ",-1)
TypeError: list indices must be integers or slices, not str
好吧,我希望你能看到这里的菜鸟失败了,你是怎么做到的?看到我会很酷,因为我是一个自学成才的新手:)
解决方案
改变
for i in file:
至
for i, line in enumerate(file):
这样,我将是一个整数索引而不是一个字符串。线是字符串。
推荐阅读
- azure - 使用 B2C 和 Active Directory 为公司实施身份验证和授权流程
- c++ - 如何根据 1) 名称和 2) 年龄对数组元素进行排序,以及输出中数组元素的匹配名称和年龄?
- javascript - 如何在 foor 循环中的 x-bind alpine.js 中添加条件?
- python - 如何在 Python 中找到一个 id 的所有孩子?
- python - Azure python Runbook 在门户中运行失败,但相同的代码在开发框中成功
- python - 如何解决python中的地理定位api错误
- powerbi - 获取当前所选月份的日期值直到前几个月
- html - 绝对 div 内的图标未居中
- ios - 如何检测光标在 iOS 中点击 UITextField 时没有改变?
- pandas - Pandas:使用 chunksize 选项读取 csv 时如何从 csv 文件末尾跳过 n 行