Python使用for循环迭代列表时跳过最后一个元素

时间:2012-08-01 10:40:06

标签: python

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
        for lst_report_footer_item in self.lst_report_footer_strings:
            print lst_temp_report_footer
            print lst_report_footer_item
            if lst_report_footer_item in ('', ' '):
                print "Inside if : Item ==" + lst_report_footer_item
                lst_temp_report_footer.remove(lst_report_footer_item)   
                print "list after remove == " + str(lst_temp_report_footer)
            else:
                print "Inside else : length = ", str(len(lst_report_footer_item))
                int_size_of_string += len(lst_report_footer_item)


if __name__ == '__main__':
    ins_class = Sample()

输出

['Manager', 'Accountant', 'Created By', 'fifth', '', '']
Manager
Inside else : length =  7
['Manager', 'Accountant', 'Created By', 'fifth', '', '']
Accountant
Inside else : length =  10
['Manager', 'Accountant', 'Created By', 'fifth', '', '']
Created By
Inside else : length =  10
['Manager', 'Accountant', 'Created By', 'fifth', '', '']
fifth
Inside else : length =  5
['Manager', 'Accountant', 'Created By', 'fifth', '', '']

Inside if : Item ==
list after remove == ['Manager', 'Accountant', 'Created By', 'fifth', '']

我需要的是......

list after remove == ['Manager', 'Accountant', 'Created By', 'fifth']

3 个答案:

答案 0 :(得分:1)

这相当于你的类,没有调试打印,以及缩短的变量名。

class Sample:
   def __init__(self):
       self.footers = ['Manager', 'Accountant', 'Created By', 'fifth', '', '']
       self.footers = [x for x in self.footers if x.strip() != ""]
       self.int_size_of_string = sum(len(x) for x in self.footers)

if __name__ == '__main__':
    myclass = Sample()
    print myclass.footers
    print myclass.int_size_of_string

我还将int_size_of_string作为属性,否则__init__完成后无法访问该属性(您无法从__init__返回值)。 strip方法从字符串的两端删除任意数量的空格和其他空白字符。

您的代码无效的原因是因为您在迭代时修改了列表。您删除了倒数第二个项目,因此最后一个项目取代了它,然后当它移动到下一个项目时,没有剩余项目了。

答案 1 :(得分:1)

我把它变成了一个更简单的代码片段,试图找出你真正想做的事情。有很多不必要的代码,你为什么要用一个类来说明你的问题呢?

>>> x=['Manager', 'Accountant', 'Created By', 'fifth', '', '']
>>> result = [i for i in x if i.strip()]
>>> result
['Manager', 'Accountant', 'Created By', 'fifth']
>>>

答案 2 :(得分:0)

好吧,它不起作用的原因是你的循环遍历列表中的每个项目。 当它找到一个空格时,它会删除该项目。并显示您当前的列表。所以第一次,它会显示空间,因为它有2个。

但是,现在你的循环失败了,因为你已经在循环中修改了列表,因此没有更多项可以循环,因为你在第5项中的第5项,然后你删除了第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()

注意 - 这个文件中的标签有些奇怪,我希望它可以为你排序。

相关问题