(二)colletions模块总结,跳出3重循环代码总结,替换文件中某一字段代码总结
来源:互联网 发布:云led控制软件 编辑:程序博客网 时间:2024/06/13 06:07
# -*- coding:utf-8 -*-from collections import Counter, OrderedDict, defaultdict, namedtuple, deque# Counter是对字典类型的补充,用于追踪值的出现次数。# ps:具备字典的所有功能 + 自己的功能print("Counter".center(50, "-"))c = Counter('abcdeabcdabcaba')print(c.most_common(3))print(''.join(c.elements()))print(''.join(sorted(c.elements())))print(''.join(sorted(c)))print(c['b'])c['b'] -= 3print(c['b'])print(''.join(c.elements()))# orderdDict是对字典类型的补充,他记住了字典元素添加的顺序# 见博客http://blog.csdn.net/liangguohuan/article/details/7088304,写的已经足够好了print("orderDict".center(50, "-"))d1 = {}d1['a'] = 'A'd1['b'] = 'B'd1['c'] = 'C'd2 = OrderedDict()d2['a'] = 'A'd2['b'] = 'B'd2['c'] = 'C'print(d1 == d2)d3 = OrderedDict()d3['b'] = 'B'd3['a'] = 'A'd3['c'] = 'C'print(d2 == d3)# Python collections.defaultdict() 与 dict的使用和区别# http://www.pythontab.com/html/2013/pythonjichu_1023/594.htmlprint('defaultdict'.center(50, '-'))values = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]my_dict1 = defaultdict(list)for value in values: if value > 66: my_dict1['k1'].append(value) else: my_dict1['k2'].append(value)print(my_dict1)my_dict2 = {}for value in values: if value > 66: my_dict2.setdefault('k1', []).append(value) else: my_dict2.setdefault('k2', []).append(value)print(my_dict2)print(my_dict1['x'])print(my_dict1)s = 'mississippi'd = defaultdict(int)for k in s: d[k] += 1print(list(d.items()))# 根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。# 博客地址http://blog.csdn.net/wukaibo1986/article/details/8188906print("nametuple".center(50, "-"))Bob = ('bob', 30, 'male')Jane = ('Jane', 29, 'female')for people in[Bob, Jane]: print("%s is %d years old %s" % people)Person = namedtuple('Person', 'name age gender')print('Type of Person:', type(Person))Bob = Person(name='Bob', age=30, gender='male')print('Representation:', Bob)Jane = Person(name='Jane', age=29, gender='female')print('Field by Name:', Jane.name)for people in[Bob, Jane]: print("%s is %d years old %s" % people)# 双向队列(deque)# 一个线程安全的双向队列print("deque".center(50, "-"))q = deque('abaacdefgh')print(q)q.append('x')print(q)q.appendleft(3)print(q)print(q.count('a'))q.extend(['a','b'])print(q)q.extendleft(['a', 'b', 'c'])print(q)print(q.pop())print(q.popleft())print(q)q.remove(3)print(q)q.reverse()print(q)# 单向队列,是先进先出(FIFO),使用了queue模块,其中单项和双项队列均有。# Queue是一个队列的同步实现。队列长度可为无限或者有限。# 可通过Queue的构造函数的可选参数maxsize来设定队列长度。如果maxsize小于1就表示队列长度无限。import queueprint("Queue".center(50, "-"))q = queue.Queue(maxsize = 2)q.put(1)q.put(2)# q.put('a', block=False) # 如果队列当前已满且block为True(默认),put()方法就使调用线程暂停,直到空出一个数据单元。如果block为False,put方法将引发Full异常。# q.put_nowait(3) # 相当q.put(3, block=False)print(q.get())print(q.get())# print(q.get(block=False)) # 调用队列对象的get()方法从队头删除并返回一个项目。可选参数为block,默认为True。如果队列为空且block为True,get()就使调用线程暂停,直至有项目可用。如果队列为空且block为False,队列将引发Empty异常。# print(q.get(timeout=2)) # 等待2秒后仍然为空则报异常,常用于多线程
输出
---------------------Counter----------------------[('a', 5), ('b', 4), ('c', 3)]bbbbecccaaaaaddaaaaabbbbcccddeabcde41becccaaaaadd--------------------orderDict---------------------TrueFalse-------------------defaultdict--------------------defaultdict(<class 'list'>, {'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55, 66]}){'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55, 66]}[]defaultdict(<class 'list'>, {'k1': [77, 88, 99, 90], 'k2': [11, 22, 33, 44, 55, 66], 'x': []})[('i', 4), ('s', 4), ('p', 2), ('m', 1)]--------------------nametuple---------------------bob is 30 years old maleJane is 29 years old femaleType of Person: <class 'type'>Representation: Person(name='Bob', age=30, gender='male')Field by Name: JaneBob is 30 years old maleJane is 29 years old female----------------------deque-----------------------deque(['a', 'b', 'a', 'a', 'c', 'd', 'e', 'f', 'g', 'h'])deque(['a', 'b', 'a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'x'])deque([3, 'a', 'b', 'a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'x'])3deque([3, 'a', 'b', 'a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'x', 'a', 'b'])deque(['c', 'b', 'a', 3, 'a', 'b', 'a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'x', 'a', 'b'])bcdeque(['b', 'a', 3, 'a', 'b', 'a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'x', 'a'])deque(['b', 'a', 'a', 'b', 'a', 'a', 'c', 'd', 'e', 'f', 'g', 'h', 'x', 'a'])deque(['a', 'x', 'h', 'g', 'f', 'e', 'd', 'c', 'a', 'a', 'b', 'a', 'a', 'b'])----------------------Queue-----------------------12
跳出三重循环(一般也没人会去跳出三重循环。。。算是一种技巧吧):
# -*- coding:utf-8 -*-# don't make your programs have too many layers# if you do have that many layers, try to use the funciton feature.break_flag1 = Falsebreak_flag2 = Falsebreak_flag3 = Falsewhile not break_flag1: print('the first layer is running...') option = input(">>>[b:back, q:quit, c:continue]") if option == 'q': break_flag1 = True elif option == 'b': break_flag1 = True else: break_flag2, break_flag3 = False, False # continue while not (break_flag2 or break_flag1): print('the second layer is running...') option = input(">>>[b:back, q:quit, c:continue]") if option == 'b': break_flag2 = True elif option == 'q': break_flag1 = True else: break_flag3 = False # continue while not (break_flag1 or break_flag2 or break_flag3): print('the third layer is running...') option = input(">>>[b:back, q:quit, c:continue]") if option == 'b': break_flag3 = True elif option == 'q': break_flag1 = True修改文件中某个字段方法(建立一个新文件,把旧文件的内容一行一行写到新文件里去即可):
old.txt:
yangkaialexnihaook将alex替换为ALEX LI...
import os# 替换原文件中的某个字段,方法是新写一个文件f = open('old.txt', 'r')f_new = open('new.txt', 'w')for line in f: if line.startswith('alex'): new_line = line.replace('alex', "ALEX LI...") f_new.write(new_line) else: f_new.write(line)f.close()f_new.close()os.rename('new.txt', 'old.txt')
0 0
- (二)colletions模块总结,跳出3重循环代码总结,替换文件中某一字段代码总结
- 重构代码总结
- java中对跳出多重循环的知识总结
- VB常用代码总结(二)【转】
- 代码规范问题总结(二)
- DirectX小段代码总结(二)
- 对跳出多层循环的方法总结
- Break 等各种跳出循环 总结
- Java 跳出多重循环的方法总结
- 代码总结
- 代码总结
- 总结代码
- 代码总结
- 代码总结
- 代码总结
- 代码总结
- 代码总结
- 代码总结
- NSData+Base64
- Retrofit
- leetcode系列(76)Remove Linked List Elements
- 逐梦C++之二:输入与输出
- HDOJ 5615 Jam's math problem (数学题枚举)
- (二)colletions模块总结,跳出3重循环代码总结,替换文件中某一字段代码总结
- iOS使用DES加解密
- android布局的复用
- java入门实例之小试牛刀--利用Scanner制作个人简历
- LeetCode152. Maximum Product Subarray
- The vertically scrolling ScrollView should not contain another vertically scrolling widget (ListView
- 对称加密 非对称加密 不可逆加密算法
- 如何将word文件转化为Latex文件:word-to-latex-2.56详解
- HDOJ 5616 Jam's balance (暴力)