【发布时间】:2016-03-12 11:31:04
【问题描述】:
我的任务是将字符串 'AAAABBBCCDAABBB' 放入这样的列表中:['A','B','C','D','A','B']
我现在为此工作了 2 个小时,但我无法找到解决方案。到目前为止,这是我的代码:
list = []
string = 'AAAABBBCCDAABBB'
i = 1
for i in string:
list.append(i)
print(list)
for element in list:
if list[element] == list[element-1]:
list.remove(list[element])
print(list)
我是编程新手,总是出现错误“TypeError: list indices must be integers or slices, not str”...
我已经更改了比较
if list[element] == list[element-1]
到
if list[element] is list[element-1]
但错误保持不变。我已经用谷歌搜索了几次,但总是有不需要字符串格式的列表,但我需要它(对吗?)。
感谢您的帮助! 无抗体
【问题讨论】:
-
元素是
string,可迭代的索引必须是数字而不是字符串 -
在
element in list中,element是列表元素,而不是列表索引。如果需要索引,请使用for index in range(len(list))或for index,element in enumerate(list)。 -
正如 danidee 所说,当您说 for element in list 时,您正在获取列表中的实际项目而不是项目的索引。因此,您以后不能做 list[element]
标签: string list python-3.x int typeerror