python进阶学习chapter02(列表、字典、集合操作)

  1. 如何在列表、字典、集合中筛选数据
  2. 列表(元组)的重命名
  3. 词频统计的实现
  4. 字典的排序
  5. 寻找多个字典的公共键
  6. 如何让字典保持有序
  7. 如何保持历史纪录(使用deque队列)

一、如何在列表、字典、集合中筛选数据

  问题引入:

列表:[-10,2,2,3,-2,7,6,9] 找出所有的非负数

字典:{1:90,2:55,3:87...} 找出所有值大于60的键值对

集合:{2,3,8,6,7,5} 找出所有被3整除的数

 列表:

#方法一,迭代
data=[1,5,-4,-6,0,7,9]
res=[]
for num in data:
    if num >=0:
        res.append(num)
print(res)
#方法二,过滤函数filter
res1=filter(lambda x:x>0,data)
print(list(res1))
#方法三,列表生成器
[x for x in data if x >= 0]  

 字典:

#字典
students={x:randint(30,100) for x in range(1,21)}
print(students)
#筛选处成绩80分以上的,items()会同时遍历键和值
res4={k:v for k,v in students.items() if v>=90}
print(res4)

集合:

#集合
set=set(data)
res5={x for x in set if x%2==0}
print(res5)

二、列表(元组)的重命名

问题引入:

1 = ('sun','25','girl','mesunyueru@qq.com')
print(s1[0])

使用数字作为数组的索引,读取的时候可读性太差了,可以改一下命名

NAME=0
AGE=1
SEX=2
EMAIL=3
print(s1[AGE])

或者导入namedtuple

from collections import namedtuple
students=namedtuple('Student',['name','age','sex','email'])#定义一个类
s2=students('sun','25','girl','mesunyueru@qq.com')#实例化一个类
print(type(s2))
print(s2.email)#相当于调用实例的属性

三、词频统计的实现

问题引入:

[6, 7, 5, 9, 4, 1, 8, 6, 2, 9]

希望统计各个元素出现的次数,可以看作一个词频统计的问题。

我们希望最终得到一个这样的结果:{6:2, 7:1...}即 {某个元素:出现的次数...}

#方法一
list=[randint(1,10) for x in range(10)]
print(list)
d=dict.fromkeys(list,0)
for x in list:
    d[x]+=1
print(d)

#方法二
from collections import Counter
d1=Counter(list)
print(d1)
print(d1.most_common(3))

dict.fromkeys()方法是用于创建一个新字典,传入两个参数,序列和初始值。http://www.runoob.com/python/att-dictionary-fromkeys.html

collections的Counter 模块见下一篇介绍

四、字典的排序

问题引入:

python字典本身是无序的,每一次访问的顺序都是随机的。我们可以通过使用sorted对字典排序,但是sorted函数仅仅是对字典的键进行排序,没有考虑值

那如果需要对下面这个字典按值排序呢?{'Tom': 87, 'Jack': 90, 'Rose': 100.....}

方法一,使用zip函数将字典的每一对(值,键)打包成元组,再用sorted排序。zip函数:http://www.runoob.com/python/python-func-zip.html

dict={x:randint(60,100) for x in 'abcdef'}
print(dict)
print(sorted(zip(dict.values(),dict.keys())))

 方法二,sorted函数本身是可以传入一个key的,然后可以按照这个指定的key排序,sorted函数还是很强大的,http://www.runoob.com/python/python-func-sorted.html

students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>> sorted(students, key=lambda s: s[2])            # 按年龄排序
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

  

五、寻找多个字典的公共键

问题引入:如何寻找三场比赛中,每场都有进球的球员呢

先生成模拟数据:

from random import randint,sample
s1 = {x: randint(1,3) for x in sample('abcdef', randint(3, 6))}
s2 = {x: randint(1,3) for x in sample('abcdef', randint(3, 6))}
s3 = {x: randint(1,3) for x in sample('abcdef', randint(3, 6))}

{'c': 1, 'e': 3, 'b': 1}
{'c': 3, 'd': 1, 'b': 2}
{'e': 3, 'a': 2, 'f': 2, 'b': 1}

 方法一,遍历

res=[]
for x in s1:
if x in s2 and x in s3:
res.append(x)
print(res)

['b']

 方法二,与运算

print(s1.keys()&s2.keys()&s3.keys())

 方法三,使用map和reduce。map和reduce的用法之后文章单独介绍

>>> map(dict.viewkeys, [s1, s2, s3])
[dict_keys(['a', 'b', 'f']), dict_keys(['a', 'b', 'e', 'd', 'g', 'f']), dict_keys(['a', 'b', 'e', 'd', 'f'])]
>>> reduce(lambda x,y: x&y, map(dict.viewkeys, [s1, s2, s3]))
set(['a', 'b', 'f']) 

五、如何让字典保持有序

字典本身是无序的,如果需要在访问的时候保持是录入时候的顺序,可以使用collections的OrderedDict

from collections import OrderedDict
d=OrderedDict()
d['sun']=(1,35)
d['yue']=(2,37)
d['ru']=(3,40)
for i in d:
    print(i)


sun
yue
ru

  

六、保存历史记录(使用deque队列)

如何保存一个猜数字游戏中你已经猜过的数字呢

先看一下没有保存的猜数字游戏的版本:

from collections import deque
from random import randint

N = randint(0, 100)


def guess(k):
    if k == N:
        print "right"
        return True
    if k < N:
        print "%s is less-than N" % k
    if k > N:
        print "%s is greater-than N" % k
    return False

while True:
    line = raw_input("please input a number:")
    if line.isdigit():
        k = int(line)
    
        if guess(k):
            break
  

  如果将每次猜的数字都存放在队列中,如果用户输入history就输出猜过的数字,版本二:

from collections import deque
from random import randint

N = randint(0, 100)
history = deque([], 5)

def guess(k):
    if k == N:
        print "right"
        return True
    if k < N:
        print "%s is less-than N" % k
    if k > N:
        print "%s is greater-than N" % k
    return False

while True:
    line = raw_input("please input a number:")
    if line.isdigit():
        k = int(line)
        history.append(k)
        if guess(k):
            break
    elif line == "history" or line == "h?":
        print list(history)

  如果还需把这个队列保存下来,下次重新执行程序的时候还可以用呢,可以使用pickle模块

先保存

>>> import pickle
>>> s = [1, 2, 3, 4, 5]
>>> pickle.dump(s, open('object', 'w'))
>>> # 这样就将s对象存在了object这个文件中,并且这个文件有一个写权限

下次可以读

>>> import pickle
>>> s = pickle.load('object')
>>> s
[1, 2, 3, 4, 5]

  

原文地址:https://www.cnblogs.com/mesunyueru/p/9196002.html