通过代码实例了解Python3编程技巧

高效处理数据类型方法:

处理数据

In [1]: from random import randint

In [2]: data=http://www.cppcns.com/jiaoben/python/[randint(-10,10) for _ in range(10)]

In [3]: data
Out[3]: [-3, -4, 3, 4, 7, -2, -4, 1, 7, -9]

#过滤列表中的负数
In [9]: list(filter(lambda x:x>=0,data))
Out[9]: [3, 4, 7, 1, 7]

[for x in data if x>=0]
# 列表生成式解法
[x for x in data if x>=0]

#哪个更快,列表解析更快,远快于迭代
In [15]: %timeit [x for x in data if x>=0]
581 ns ± 23.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [16]: %timeit filter(lambda x:x>=0,data)
237 ns ± 4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

#得到20个同学的成绩
d={x:randint(60,100)for x in range(1,21)}
#字典解析式,iteritems同时迭代字典,
#
#得到分数大于90的同学
{k:v for k,v in d.items() if v>90}


#集合解析
In [35]: {x for x in s if x %3 ==0}
Out[35]: {-9, -3, 3}

#为元祖中的每个元素命名,提高程序可读性
#元祖存储空间小,访问速度快
#定义常量
NAME = 0
AGE=1
SEX=2
EMAIL=3
#拆包用法,定义类似其他语言的枚举类型,也就是定义数值常量
NAME,AGE,SEX,EMAIL=range(4)

#案例
student=('Jim',16,'male','jin@163.com')
#name
print(student[0])
#age
print(student[1])
#通过常量可以优化为
print(student[NAME])
print(student[AGE])

#namedtuple是继承自tuple的子类,namedtuple和tuple比较有更酷的特性
#namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性。这对象更像带有数据属性的类,不过数据属性是只读的。
from collections import namedtuple
Student = namedtuple('Student',['name','age','sex','email'])
s=Student('Jim',16,'male','jim@163.com')
s.name 
s.age

#统计序列中元素出现的频度
from random import randint
data=[randint(0,20) for _ in range(30)]
#创建字典{0:0,1:0,...}
#方法1
c=dict.fromkeys(data,0)
In [52]: for x in data:
  ...:   c[x]+=1

#方法2,统计词频
from collections import Counter
c2=Counter(data)#讲序列传入Counter的构造器,得到Counter对象是元素频度的字典
#使用most_common统计词频
In [58]: c2.most_common(3)
Out[58]: [(10, 4), (20, 3), (8, 3)]
#统计英文作文词频
import re
txt=open('emmmm.txt').read()
#分割后赋给Counter
c3=Counter(re.split('\W',txt))
#找到频率最高的10个单词
c3.most_common(10)

#内置函数是以c的速度运行,如sorted
from random import randint 
d={x:randint(60,100) for x in 'xyzabc'}
#{'a': 91, 'b': 65, 'c': 76, 'x': 85, 'y': 84, 'z': 72}
# sorted(d)
In [15]: zip(d.values(),d.keys())
Out[15]: <zip at 0x108b34dc8>

In [16]: list(zip(d.values(),d.keys()))
Out[16]: [(68, 'x'), (70, 'y'), (77, 'z'), (72, 'a'), (65, 'b'), (69, 'c')]

#快速找到多个字典中的公共键
#In [1]: from random import randint,sample

In [2]: sample('abcdefg',3)
Out[2]: ['c', 'a', 'b']


In [4]: sample('abcdefg',randint(3,6))
Out[4]: ['b', 'a', 'd']

In [5]: s1={x:randint(1,4)for x in sample('abcdefg',randint(3,6))}

In [9]: s1
Out[9]: {'a': 1, 'b': 2, 'c': 3, 'f': 3, 'g': 3}

In [10]: s1={x:randint(1,4)for x in sample('abcdefg',randint(3,6))}

In [11]: s1
Out[11]: {'b': 2, 'd': 3, 'g': 3}

In [12]: s1
Out[12]: {'b': 2, 'd': 3, 'g': 3}

In [13]: s2={x:randint(1,4)for x in sample('abcdefg',randint(3,6))}

In [15]: s3={x:randint(1,4)for x in sample('abcdefg',randint(3,6))}
#for循环遍历方法,找到s2,s3都有的k
In [19]: res=[]

In [20]: for k in s1:
  ...:   if k in s2 and k in s3:
  ...:     res.append(k
  ...:     )
  ...:     
  ...:     

In [21]: res
Out[21]: ['b']
#通过字典的keys()方法,找到三个字典同样的key
In [26]: s1.keys()&s2.keys()&s3.keys()
Out[26]: {'b'}
#通过map得到一个迭代器对象
#In [27]: map(dict.keys,[s1,s2,s3])
Out[27]: <map at 0x108891b70>

In [28]: list(map(dict.keys,[s1,s2,s3]))
Out[28]: 
[dict_keys(['g', 'd', 'b']),
 dict_keys(['g', 'a', 'c', 'b', 'f']),
 dict_keys(['d', 'f', 'b', 'c', 'e', 'a'])]
#通过reduce取出同样结果
In [30]: from functools import reduce

In [31]: reduce(lambda a,b:a&b,map(dict.keys,[s1,s2,s3]))
Out[31]: {'b'}

#使得
from time import time
from random import randint
from collections import OrderedDict

d=OrderedDict()
players = list("ABCDEFGH")
start=time()
for i in range(8):
  input()
  p=players.pop(randint(0,8-i))
  end=time()
  print(i+1,p,end-start)
  d[p]=(i+1,end-start)
print('')
print('-'*20)
for k in d:
  print(k,d[k])
#查看用户历史记录功能,标准库collections的deque,双端循环队列,存在内容中,pickle存储到文件
from random import randint
from collections import deque
N = randint(0,100)
history = deque([],5)
def guess(K):
  if K ==N:
   print('正确')
   return True
  if K < N:
   print('%s is less-than N'%K)
  else:
    print("%s is greater-than N"%K)
  return False
while True:
  line = input("请输入一个数字:")
  if line.isdigit():
   k=int(line)
   history.append(k)
   if guess(k):
     break
  elif line =='history' or line =='h?':
    print(list(history))

通过代码实例了解Python3编程技巧

扫一扫手机访问