首页 > 解决方案 > 我需要帮助修复此列表的索引错误,请

问题描述

我正在尝试重新排序列表,而不是像这样:

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

有人可以帮我解决这个错误吗?

标签: python-3.x

解决方案


该错误很可能是由于您传递了“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'
        )


推荐阅读