파이썬에서 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
'for i in range (len (foo))'는 항상 Python에서 뭔가 잘못하고 있다는 신호입니다. –
@DanielRoseman 이것이 왜 그렇게 복잡한 지 알 수 있습니까? – user3501855
일반적으로 코드는 다른 언어에서 문자 그대로 번역되었다는 표시입니다. 파이썬에서는 일반적으로 인덱스가 아닌 요소를 반복합니다. 만약 당신이 정말로 인덱스가 필요하다면'for i, elem in enumerate (foo)'는 훨씬 더 파이썬적인 방법입니다. –