python基础之路

dict字典:

创建字典:

person = {'name':'fush','age':28}或者person = dict({'name':'fush','age':28})

字典的取值:

person = {'name':'fush','age':28}
  print(person.keys())

输出:

dict_keys(['name', 'age'])


print(person.values())

输出:

dict_values(['fush', 28])


for i in person.keys():
  print(i)

输出:

name
age


for a in person.values():
  print(a)

输出:

fush
28


for j,k in person.items():
  print(j,k)

输出:

name fush
age 28

set集合:

s1 = set([11,22,44])
s2 = set([22,33])

ret1 = s1.difference(s2)                            #取出自己与S2不同的元素,组成一个集合;
ret2 = s1.symmetric_difference(s2)            #取出S1与S2没有交集的元素,组成一个新的集合;
print(ret1)
print(ret2)

执行结果:

{11, 44}
{33, 11, 44}

counter计数器:

import collections   #需要导入collections模块

c = collections.Counter('abcdeabcdabcaba')    # count elements from a string
print(c)
ret = c.most_common(3)
print(ret)

 输出结果:

Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
[('a', 5), ('b', 4), ('c', 3)]

| >>> c.most_common(3)   # three most common elements   取前三个
| [('a', 5), ('b', 4), ('c', 3)]
| >>> sorted(c) # list all unique elements    列出所有唯一的元素
| ['a', 'b', 'c', 'd', 'e']
| >>> ''.join(sorted(c.elements())) # list elements with repetitions
| 'aaaaabbbbcccdde'
| >>> sum(c.values()) # total of all counts     统计次数
| 15
|
| >>> c['a']   # count of letter 'a'   ‘a’ 出现的次数
| 5

栈:后进先出(弹夹原理)

单项队列:先进先出

单项队列:

import queue            #单项队列需要导入queue模块
q = queue.Queue()
q.put('123')                #put 为放
q.put('345')                
print(q.qsize())

print(q.get())              #get 为取

输出:

2                   ##队列的大小
123               ##根据先进先出原理,取得是123

双向队列:

import collections

d = collections.deque()
d.append('123')              
d.appendleft('456')
d.extend([11,22,33])
d.extendleft(['fush','shan'])
print(d)

d.rotate(1)        #将最后一个拿到最左边,d.rotate(3)  则是最右边3个拿到左边
print(d)

输出:

deque(['shan', 'fush', '456', '123', 11, 22, 33])
deque([33, 'shan', 'fush', '456', '123', 11, 22])         #d.rotate(1)

deque([11, 22, 33, 'shan', 'fush', '456', '123'])         #d.rotate(3)

深浅拷贝:

import copy
dic = {
'cpu':[80,],
'men':[80,],
'disk':[80,]
}

print('before:',dic)
new_dic = copy.copy(dic)    #浅拷贝
new_dic['cpu'][0] = 50
print(dic)
print(new_dic)

输出:

before: {'cpu': [80], 'men': [80], 'disk': [80]}
{'cpu': [50], 'men': [80], 'disk': [80]}                  #浅拷贝,原先的也会被改掉
{'cpu': [50], 'men': [80], 'disk': [80]}

import copy
dic = {
'cpu':[80,],
'men':[80,],
'disk':[80,]
}

print('before:',dic)
new_dic = copy.deepcopy(dic)    #深拷贝
new_dic['cpu'][0] = 50
print(dic)
print(new_dic)

before: {'men': [80], 'disk': [80], 'cpu': [80]}
{'men': [80], 'disk': [80], 'cpu': [80]}            #深拷贝,原先的木有变化
{'disk': [80], 'cpu': [50], 'men': [80]}

迭代器:

names = iter(['fu','shan','hua'])
print(names.__next__())     #python 3.0
print(names.__next__())
print(names.__next__())

输出:

fu
shan
hua

python 2.0

names = iter(['fu','shan','hua'])

In [45]: print names.next()
fu

In [46]: print names.next()
shan

In [47]: print names.next()
hua

例子:把列表的每个元素加1

第一种方法:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a = map(lambda x:x+1, a)

a

[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

第二种方法:

In [19]: [i+1 for i in range(1,11)]
Out[19]: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

生成器generator

定义:一个函数调用时返回一个迭代器,那这个函数就叫做生成器(generator),如果函数中包含yield语法,那这个函数就会变成生成器 

def cash_meney(amount):
while amount > 0:
  amount -= 100
  yield 100                           #这里的yield是返回值100
  print('又来取钱啦')
atm = cash_meney(500)
print(atm.__next__())
print(atm.__next__())
print("花完了再来取钱")
print(atm.__next__())

作用:

这个yield的主要效果呢,就是可以使函数中断,并保存中断状态,中断后,代码可以继续往下执行,过一段时间还可以再重新调用这个函数,从上次yield的下一句开始执行。

另外,还可通过yield实现在单线程的情况下实现并发运算的效果

下面这个例子很经典(引用alex老师):

import time
def consumer(name):
  print("%s 准备吃包子啦!" %name)
  while True:
    baozi = yield

    print("包子[%s]来了,被[%s]吃了!" %(baozi,name))

def producer(name):
  c = consumer('A')
  c2 = consumer('B')
  c.__next__()
  c2.__next__()
  print("老子开始准备做包子啦!")
  for i in range(10):
    time.sleep(1)
    print("做了2个包子!")
    c.send(i)                             ###通过send 向yield传值
    c2.send(i)

producer("alex")

装饰器(给已经实现的功能扩展功能):

def w1(func):
  def inner(arg):
    print('passwd to ....')
    return func(arg)
  return inner

@w1
def f1(arg):
  print('welcome [%s] to TV page ' % arg)

f1('fush')

输出结果:

passwd to ....
welcome [fush] to TV page

原文地址:https://www.cnblogs.com/shanhua-fu/p/6893142.html