python-3.x - 我需要帮助修复此列表的索引错误,请
问题描述
我正在尝试重新排序列表,而不是像这样:
Boris, 1, Johnson
Noah, 2, Miller
Liam, 3, Johnson
看起来像这样
Boris Johnson, 1
Noah Miller, 2
Liam Johnson, 3
我的代码如下所示:
firstNames = []
numbers = []
lastNames = []
with open("lab9data.txt") as f:
contents = f.readlines()
for i in contents:
x, y, z = i.split(',')
firstNames.append(x)
numbers.append(int(y))
lastNames.append(z)
f.write(firstNames[i]+lastNames[i]+', '+(str(numbers[i]))+'\n')
print(firstNames[0]) #test
print(numbers[0]) #test
print(lastNames[0]) #test
当我尝试运行此代码时,它会收到一条错误消息:
TypeError: list indices must be integers or slices, not str
有人可以帮我解决这个错误吗?
解决方案
该错误很可能是由于您传递了“i”,它是一个字符串作为访问列表项目的索引值。
print(i)
>>> 'Boris, 1, Johnson'
尝试类似的东西
For index, i in enumerate(contents):
...
...
... firstNames[index] + lastNames[index] ...
您还将在 f.write() 处收到错误,因为您已以只读方式打开文件。
这是完整的答案。
with open('lab9data.txt') as f1, \
open('lab9data_2.txt', 'w') as f2:
contents = f1.readlines()
for i in contents:
# The strip function removes whitespace and newlines.
first_name, number, last_name = [
string.strip(' ').strip('\n') for string in i.split(',')
]
f2.write(first_name
+ ' '
+ last_name
+ ', '
+ number
+ '\n'
)
推荐阅读
- php - Mailchimp API 'marketing_permissions' 字段始终无法通过“此值应为数组类型”的验证
- django - 如何为 Djoser 电子邮件使用不同的域?
- assembly - nasm(x86_64 System V ABI)可移植方式确定使用的堆栈内存?
- tensorflow - 如何修复我的新笔记本电脑运行 tensorflow-gpu 2.1 的能力
- javascript - 如何加快 JavaScript 图像加载
- assembly - 重定位应该如何在静态 PIE 二进制文件中工作?
- .net - 在不使用 azcopy 的情况下跨 Azure 容器复制文件
- java - 什么是列表节点?为什么 List Node 的 return 语句返回数组而不是 Node?
- java - 计算星期几JAVA
- javascript - React Native 类型的函数