2014-12-03 83 views
0

我不得不回答的問題是:添加一個列表的所有值到另一個

與簽名

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]取出,並等同於lislis[i]lis[i-1]刪除列表。
  • 否則,發生的所有情況是從lis中刪除了lis[i]

我寫了這個問題的代碼是:

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

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 
+0

不,pythonic方式將不會試着用'i'來索引,而是直接使用'i' * *。或者使用'enumerate()'來獲取索引和對象。 – 2014-12-03 17:24:42

+0

此外,代碼中還有許多其他問題,一旦解決了這個特定的異常,就會崩潰。 – 2014-12-03 17:25:29

+0

等待代碼還有什麼問題? – 2014-12-03 17:25:29

相關問題