zoukankan      html  css  js  c++  java
  • python3用list实现栈

    工作中遇到的需求,****代表标签数据别的信息:

    D01  ********  1  ********

    D01  ********  2  ********

    D01  ********  3  ********

    D01  ********  4  ********

    D02  ********  1  ********

    D02  ********  2  ********

    ......后面还有好多。

    要变成:

    D01  ********  4  ********

    D01  ********  3  ********

    D01  ********  2  ********

    D01  ********  1  ********

    D02  ********  2  ********

    D02  ********  1  ********

    ......

    相当于把标签(红色字体)是一样的,进栈,再出栈,出栈的结果放进list里。

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    
    def main():
      pass
    
    if __name__ == "__main__":
      f = open("info", 'r')
      list_info = []
      list_temp = []
      last_field = "D01"
      for line in f:
        new_field = line.split()[0]
        if new_field == last_field:
          list_temp.append(line)
        else:
          while(list_temp):
            list_info.append(list_temp.pop())
          last_field = new_field
          list_temp.append(line)
      while(list_temp):
        list_info.append(list_temp.pop())
      for item in list_info:
        print(item, end='')
    
      f.close()
      main()

    最后一个标签的数据需要单独出栈,追加到最终的list里。

  • 相关阅读:
    设计模式之观察者模式
    设计模式之代理模式
    用Javascript模拟微信飞机大战游戏
    [Leetcode] Remove Duplicates from Sorted List II
    [Leetcode] Remove Duplicates from Sorted List
    [Leetcode] Remove Duplicates from Sorted Array II
    [Leetcode] Palindrome Number
    [Leetcode] Decode Ways
    [Leetcode] Climbing Stairs
    [Leetcode] Maximum Subarray
  • 原文地址:https://www.cnblogs.com/donggongdechen/p/8686027.html
Copyright © 2011-2022 走看看