天天看點

python for 循環中最後一個不要_Python在使用for循環疊代清單時跳過中的最後一個元素...

好吧,它不起作用的原因是因為循環周遊了清單中的每一項。

當它找到一個空格時,它會删除該項。并顯示目前清單。是以第一次,它會顯示空間,因為有兩個。在

但是,現在你的循環失敗了,因為你在循環中修改了清單,是以沒有更多的項目可供它疊代,因為你在第5項中的第6項,然後你删除了第5項,現在清單隻包含5項,但循環查找第6項。既然沒有,就退出。讓名單保持原樣。在

基本上,你應該做的是:class Sample:

def __init__(self):

self.lst_report_footer_strings = \

['Manager', 'Accountant', 'Created By', 'fifth', '', '']

int_size_of_string = 0

lst_temp_report_footer = self.lst_report_footer_strings

temp_remove_list = []

for lst_report_footer_item in xrange(len(self.lst_report_footer_strings)):

print lst_temp_report_footer

print self.lst_report_footer_strings[lst_report_footer_item]

if lst_temp_report_footer[lst_report_footer_item] in ['',' ']:

print "Inside if : Item =="+self.lst_report_footer_strings[lst_report_footer_item]

temp_remove_list.append(lst_report_footer_item)

else:

print "Inside else : length = ",str(len(lst_temp_report_footer[lst_report_footer_item]))

int_size_of_string += len(lst_temp_report_footer[lst_report_footer_item])

for item in reversed(temp_remove_list):

del lst_temp_report_footer[item]

print "final list : == ",lst_temp_report_footer

if __name__ == '__main__':

ins_class = Sample()

注意-這個檔案中的标簽有一些奇怪的地方,希望你能了解。在