2014-04-05 4 views
0

파이썬에서 HTML에 간단한 4 열 테이블을 생성하는 함수를 작성했습니다. 파일에서 호출하면 표가 올바르게 반환됩니다.여러 번 호출했을 때 파이썬 함수가 오동작을합니다.

그러나 단일 스크립트에서 여러 번 호출되는 경우 문제가 발생합니다. 첫 번째 것은 꼭해야 할 것처럼 보입니다. 두 번 호출 될 때 제목 행 아래의 모든 행에는 네 개 대신 여섯 개의 열 (두 개의 공백)이 있습니다. 세 번째로, 열 (열 여섯 개)이 비어 있습니다.

나는 코딩 작업을 최근에 시작 했으므로 여기서 어떤 일이 일어나고 있는지 잘 모릅니다.

함수가 연속으로 두 번 이상 호출되면 함수의 새 인스턴스가 호출됩니까? 변수가 모두 '재설정'되어 말합니까?

def fourColumnTable(title1, list1, title2, list2, title3, list3, title4, list4): 
    error = 0 
    #Check that the lists are all of the same length 
    if(len(list1) != len(list2) or len(list1) != len(list3) or len(list1) != len(list4)): 
     error = 1 
     table = "ERROR: The lists must all be the same length" 

    if(error == 0): 
     tableList = [] 
    #Append <table> tag 
     tableList.append('<table class="table table-bordered">') 

    #Format list elements and titles 
     #Put each title inside <th> tags 
     titleList = [] 
     titleList.append(title1) 
     titleList.append(title2) 
     titleList.append(title3) 
     titleList.append(title4) 
     for i in range(len(titleList)): 
      titleList[i] = "<th>" + str(titleList[i]) + "</th>" 

     #Put each string element inside <td> tags 
     for i in range(len(list1)): 
      list1[i] = "<td>" + str(list1[i]) + "</td>" 
     for i in range(len(list2)): 
      list2[i] = "<td>" + str(list2[i]) + "</td>" 
     for i in range(len(list3)): 
      list3[i] = "<td>" + str(list3[i]) + "</td>" 
     for i in range(len(list4)): 
      list4[i] = "<td>" + str(list4[i]) + "</td>" 

    #Put all list elements in the tableList 
     tableList.append('<thead>') 
     for i in range(len(titleList)): 
      tableList.append(titleList[i]) 
     tableList.append('</thead>') 
     tableList.append('<tbody>') 
     for i in range(len(list1)): 
      tableList.append('<tr>') 
      tableList.append(list1[i]) 
      tableList.append(list2[i]) 
      tableList.append(list3[i]) 
      tableList.append(list4[i]) 
      tableList.append('</tr>') 
     tableList.append('</tbody>') 

    #Close the <table> tag 
     tableList.append('</table>') 

    #Assign tableList to one variable 
     table = ''.join(tableList) 
    return table 
+0

'for i in range (len (foo))'는 항상 Python에서 뭔가 잘못하고 있다는 신호입니다. –

+0

@DanielRoseman 이것이 왜 그렇게 복잡한 지 알 수 있습니까? – user3501855

+0

일반적으로 코드는 다른 언어에서 문자 그대로 번역되었다는 표시입니다. 파이썬에서는 일반적으로 인덱스가 아닌 요소를 반복합니다. 만약 당신이 정말로 인덱스가 필요하다면'for i, elem in enumerate (foo)'는 훨씬 더 파이썬적인 방법입니다. –

답변

0

나는 일부 (전부는 아니지만) 귀하의 listN 인수는 호출 사이에 재사용되고 있다고 의심 :

는 호출 된 함수의 코드입니다. 이는 코드가 호출 될 때마다 제공된 목록을 수정하기 때문에 버그가 발생합니다. 각 목록 항목에 <td></td>을 추가합니다. 동일한 목록에서 반복적으로이 작업을 수행하면 항목에 여러 겹치기 태그가 생깁니다 (예 : <td><td><td>...</td></td></td>.

그러면 브라우저가 반복 태그 사이에 누락 된 닫는 태그를 채우고 끝에있는 추가 닫는 태그를 무시할 때 여분의 빈 열로 렌더링됩니다.

첫 번째 빠른 수정이 아니라 (지능형리스트를 사용하여 여기에) 제공된 목록을 수정하는 것보다, 수정 된 항목 새 목록을 작성하는 것입니다 :

list1 = ["<td>" + item + "</td>" for item in list1] 

추가적인 개선이 라이브러리를 사용하는 것 테이블을 직접 만들지 않고 직접 문자열 조작으로 만듭니다. 사용할 수있는 다양한 XML 템플릿 라이브러리가 있지만 강력한 제안을하기에 충분한 경험이 없습니다. This page은 탐색을 시작할 수있는 좋은 장소 일 수 있습니다.

+0

그랬습니다. 감사! – user3501855

관련 문제