【发布时间】:2021-04-05 01:01:56
【问题描述】:
我有两个外部文件,我已经将它们组合成一个按字母排序的列表,我需要将 A-I、J-R 和 S-Z 范围内的所有名称输出到三个不同的 .txt 文件。
# Send names beginning with A-I to new file.
for x in names:
if names[x] == ["A" "B" "C" "D" "E" "F" "G" "H" "I"]:
print('babyNamesAtoI.txt', file=f)
# Send names beginning with J-R to new file.
elif names[x] == ["J" "K" "L" "M" "N" "O", "P", "Q", "R"]:
print('babyNamesJtoR.txt', file=f)
# Send names beginning with S-Z to new file.
else:
print('babyNamesStoZ', file=f)
每次运行都会出现这个错误:
Traceback (most recent call last):
File "C:/Users/xxx/Desktop/Babynamesort.py", line 37, in <module>
if names[x] == ["A" "B" "C" "D" "E" "F" "G" "H" "I"]:
TypeError: list indices must be integers or slices, not str
【问题讨论】:
标签: python list output typeerror