我必须回答的问题是:
实施带签名的功能
def expand_one_or(course_lists):
此函数列出了字符串course_lists的列表,以及 修改如下:
- 找到
lis
中出现course_lists
的第一个列表(称之为"/"
)。- 然后找到
"/"
中第一个lis
的坐标(比如i
)。- 如果
lis[i-1]
和lis[i+1]
存在并且都是课程,lis
会在course_lists
中替换为两个新列表:与lis
相同的列表,但是 已移除lis[i]
和lis[i+1]
,以及与lis
相同的列表,但有 已删除lis[i]
和lis[i-1]
。- 否则,所有发生的事情都是从
lis[i]
移除lis
。
我为这个问题写的代码是:
def get_course_details(course_description):
beg_1 = "<A Name="
end_1 = "></A>"
for i in course_description:
course_desc1 = [course_description[i] for i in course_description]
course_desc2 = [course_description[i] for i in course_description]
course_desc1[i] = [i].replace('<a name=','<A Name=')
course_desc2[i] = course_description[i].replace('></a>','></A>')
x1 = course_desc1.find(beg_1)
y1 = course_desc2.find(end_1)
course_code = course_description[x1 + len(beg_1):y1]
course_code = course_description.replace('"','')
beg_2 = "Prerequisite:"
end_2 = "<br>"
x2 = course_description.find(beg_2)
y2_temp = course_description[x2:]
y2 = y2_temp.replace("<BR>", "<br>").find(end_2)
prerequisites = y2_temp[:y2 + 1]
course_details = []
course_details.extend([course_code, prerequisites])
return course_details
但是我一直收到错误
list indices must be integers, not str
我不知道如何解决这个问题。
答案 0 :(得分:0)
您的course_description
是一个字符串列表:
替换这个:
for i in course_description:
为:
for i in range(len(course_description)):
查看此演示,然后您将修复自己的演示:
>>> a = ['a','b','c','d']
>>> for i in a:
... print a[i] # i is the element of a not the index
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: list indices must be integers, not str
>>> for i in a:
... print i
...
a
b
c
d
>>> for i in range(len(a)): # i in an integer from 0 to len(a)
... print a[i]
...
a
b
c
d
>>> for i,x in enumerate(a): # enumerate access index and object both in tuple
... print i,x
...
0 a
1 b
2 c
3 d