ecwork

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

list与字典互换的技巧:

info = {} 
for tt in soup.select('.trl-item1'):
    value, key = tt.text.strip().split()    # 这里value, key 等于['aaa', 'bbb']这样的一个list
    info[key] = value

 

===========================================================
map使用:
map函数会对一个序列对象中的每一个元素应用被传入的函数,并且返回一个包含了所有函数调用的结果的一个列表

counters = [1, 2, 3, 4]
updated = []
for x in counters:
    updated.append(x + 10)

updated
[11, 12, 13, 14]


def inc(x): return x + 10

list(map(inc, counters))
[11, 12, 13, 14]

 

def abc(a, b, c):
    return a*10000 + b*100 + c

list1 = [11,22,33]
list2 = [44,55,66]
list3 = [77,88,99]

map(abc,list1,list2,list3)
[114477, 225588, 336699]

 

 

===========================================================

set 与list近似,但set是无序,不重复的序列

se = {"123", "456"}

 

s1 = {11, 22, 33}
s2 = {22, 33, 44}
s3 = s1.difference(S2)
# A中存在, B中不存在
print(s3)
{11}

s3 = s2.difference(s1)
print(s3)
{44}

 ===========================================================

函数

def email():
    print("我要发邮件“)
    return True

ret = email()

# 执行函数
# 函数return后面的值赋给ret
# 如果没有设置return, 默认返回None, 这样就可以根据返回的使用if判断函数是否成功

形参和实参 Parameters and arguments 

def dosomething(do):
    ...
    ...

ret = dosomething("drive")

# do为形式参数
# drive为实际参数

 

有多少个形参就要传递多少个实参

def dosomething(first, second, three):
    ...
    ...

ret = dosomething(second = "drive", three = "test", first = "one")

# 可以通过指定实形参出入实参,默认是一一对应

 

默认参数

def dosomething (do = 'drive'):
    ...
    ...

ret = dosomething()

# 形参指定默认参数,当直接调用不传入参数的话,直接使用默认参数

  

动态参数

def dosomething(*do):
    ...
    ...

dosomething(drive, stop, drive)

# 当形参加上*就成为动态参数,可以无限传入参数,作为元组tuple

def dosomething(**do):
    ...
    ...

dosomething(k1='drive', k2='stop', k3='drive')

# 当两个星的时候接收字典的方式

def dosomething(*do, **dodo):
    print(do, type(do))
    print(dodo, type(dodo)

dosomething(11,22,33,k1=123,k2=321)

# 使用*和**组合就可以既使用元祖又可以使用字典

*元组
**字典

def f1(*arges, **kwargs)

 

  

 

邮件实例

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
  
  
msg = MIMEText('邮件内容', 'plain', 'utf-8')
msg['From'] = formataddr(["武沛齐",'wptawy@126.com'])
msg['To'] = formataddr(["走人",'424662508@qq.com'])
msg['Subject'] = "主题"
  
server = smtplib.SMTP("smtp.126.com", 25)
server.login("wptawy@126.com", "邮箱密码")
server.sendmail('wptawy@126.com', ['424662508@qq.com',], msg.as_string())
server.quit()

发送邮件实例

函数中只要执行return后就会直接跳出

 

===========================================================

三元表达式

if 1 ==1:
    name = "alex"
else:
    name = "SB"
==equal==
name = "alex" if 1 == 1 else "SB"

 

lambda表达式(对简单赋值进行操作) - lambda argument1, argument2... argumentN:expression using arguments
同样的函数表达式不同的写法

def f1(arg):
    return arg + 100

result = f1(10)
print(result)
==equal==
f1 = lambda arg: arg + 100

result = f1(10)
print(result)

 

lambda表达式默认包含return功能,自动会返回函数


=========================================================

abs() - 取绝对值

n = abs(-1)
print(n)

 =========================================================

return

当函数运行到return时,会将return的数值返回出函数,并且结束函数

如果函数没有return世,python会自动返回none值

==========================================================

all() - 所有为真,才为真

# 0, None, "", [], {}, () 这些都为False
# 可以通过print(bool("")) 这样的方法进行判断

n = all([1, 2, 3])
print(n) # 返回True.

any() - 任何一个为真,即为真

n = any([[], 0, 1] )
print(n) # 返回True.

 

==========================================================

ascii() - 自动执行对象的__str__方法 (不常用)

 

========================================================== 

bin() - 接收十进制返回二进制

print(bin(5))

oct() - 接收十进制返回八进制

hex() - 接收十进制返回十六进制

 

========================================================== 

bytes() - 转换的字符串,按照什么编码

utf8 一个汉字占用三个字节 (一个字节8位), gbk 一个汉字占用二个字节

s = "李杰" # 一个汉字占用三个字节 (一个字节8位)

01010101 01010101 01010101  01010101 01010101 01010101

s = "李杰"

n = bytes(s, encoding='utf8')
print(n)

n = bytes(s, encoding='gbk')
print(n)

str() - 字节转化成字符串  

str(bytes("李杰", encoding='utf8'))

 

========================================================== 
open() - 打开文件操作( 1. 打开文件 2. 操作文件 3. 关闭文件)

with open('file') as f:
    pass

# 使用with方式操作文件,不需要另外添加f.close()的方式来关闭文件

1. 打开文件:

file = open('db', 'r')  # 只读文件
file = open('db', 'w')  # 只写文件,写前全部清空
file = open('db', 'x')  # python3.0新功能,如果这个文件存在,报错。如果不存在,创建并只写。
file = open('db', 'a')  # 追加
file = open('db', 'rb') # 使用二进制的方式读取,读出来时字节
file = open('db', 'r', endcoding="utf-8) # 如果文件出现乱码,可能在endcoding这里没有选对编码
data = f.read()    # 一次所有的文件全部读出来
print(data, type(data))
f.close
file = open('db', 'r+') # 读写
file = open('db', 'w+') # 读写
file = open('db', 'a+') # 读写
file = open('db', 'r+b) # r+b 以字节的方式来操作
f = open('db', 'r+', encoding="utf-8")    #如果打开模式无b,则read,按照字符读取
data = f.read(1)    
print(f.tell())    # tell当前指针所在的位置(字节)
f.seek(f.tell())    # 调整当前指着你的位置(字节),当前指针位置开始覆盖
f.write("777")
f.close

2. 操作文件

read()        # 无参数,全部读取
                 # 有参数,b: 按字节读取
                                无b:按字符读取

tell()          # 获取当前指针位置(字节)

seek(1)      # 跳转到指针位置(字节)

write()       # 写数据,b: 写字节;无b,写字符

close()       # 关闭文件

flush          # 强刷文件

readline()   # 仅读取一行

truncate()   # 截断,根据指针位置后的内容清空

for 循环文件对象:
f = open(xxx)
for line in f:
    print(line)

 

with 文件操作,同打开N个文件:

with expression [as variable]:
  with-block

with open('db') as f:       # 打开一个文件,不用使用close()函数,文件会自动关闭
    pass    


# 同时打开两个文件,读取一个文件,复制到另外一个文件内
with open('db1', 'r') as f1, open('db2', 'w') as f2:    # 同时打开两个文件
    times = 0
    for line in f1:
        times +=1
        if times <=10:
            f2.write(line)  
        else:
            break

# 同时打开两个文件,将文件里面的内容,Eric替代alex。
with open('db1', 'r', encoding='utf-8) as f1, open('db2', 'w', encoding='utf-8') as f2:
    for line in f1:
        new_str = line.replace('alex', 'Eric')
        f2.write(new_str)

  

  

 

posted on 2017-07-30 15:33  ecwork  阅读(262)  评论(0编辑  收藏  举报