(二)colletions模块总结,跳出3重循环代码总结,替换文件中某一字段代码总结

# -*- 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'] -= 3
print(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.html
print('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] += 1
print(list(d.items()))


# 根据nametuple可以创建一个包含tuple所有功能以及其他功能的类型。
# 博客地址http://blog.csdn.net/wukaibo1986/article/details/8188906
print("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 queue
print("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)]
bbbbecccaaaaadd
aaaaabbbbcccdde
abcde
4
1
becccaaaaadd
--------------------orderDict---------------------
True
False
-------------------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 male
Jane is 29 years old female
Type of Person: <class 'type'>
Representation: Person(name='Bob', age=30, gender='male')
Field by Name: Jane
Bob is 30 years old male
Jane 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'])
3
deque([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'])
b
c
deque(['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-----------------------
1
2

跳出三重循环(一般也没人会去跳出三重循环。。。算是一种技巧吧):

# -*- 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 = False
break_flag2 = False
break_flag3 = False

while 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:

yangkai
alex
nihao

ok
将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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
checkinList[i].bed << endl; } out.close(); } // 从文件加载入住信息 void loadFromFile() { ifstream in("checkin.txt"); string id, dormId; int bed; while (in好的,我可以帮你回答这个问题。以下是示例代码: ```java import java.util.*; public class Main >> id >> dormId >> bed) { checkIn(CheckIn(id, dormId, bed)); } in.close(); { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); Scanner scanner = new Scanner(System.in); // 输入10个整型值 System.out.println("请输入10个整数:"); for (int i = } // 统计宿舍入住率 double checkInRate() { int count = 0; for (int i = 0; i < dorList.size(); i++) { int c = 0; for (int j = 00; i < 10; i++) { int num = scanner.nextInt(); list.add(num); } // 使用Collections类的sort方法对ArrayList进行排序 Collections.sort(list); // 使用Iterator迭代器输出排序后的ArrayList ; j < checkinList.size(); j++) { if (checkinList[j].dormId == dorList[i].id) System.out.println("排序后的结果为:"); Iterator<Integer> iterator = list.iterator(); while (iterator.hasNext()) { { c++; } } count += c; } return (double) count / (dorList.size() System.out.print(iterator.next() + " "); } } } ``` 当你运行这个程序时,它会提示你 * dorList[0].capacity); } // 统计学生男女比例 double genderRatio() { int输入10个整数,然后将这10个整数添加到ArrayList。接下来,使用Collections类的sort male = 0, female = 0; for (int i = 0; i < stuList.size(); i++) { 方法对ArrayList进行排序。最后,使用Iterator迭代器遍历ArrayList并输出排序后的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值