序列

一.分类:
列表,元组,字符串(python中没有表示字符的类型,因此一个字符就是包含一个元素的字符串)

二。常见操作
1.索引:
>>> classmates = [‘Michael’, ‘Bob’, ‘Tracy’]
>>> classmates[0]
‘Michael’
>>> classmates[-1]
‘Tracy’

2.切片
①步长为1
L = [‘Michael’, ‘Sarah’, ‘Tracy’, ‘Bob’, ‘Jack’]
>>> L[0:3]
[‘Michael’, ‘Sarah’, ‘Tracy’]
>>> L[:3]
[‘Michael’, ‘Sarah’, ‘Tracy’]#从0开始索引
>>> L[1:]
[‘Sarah’, ‘Tracy’, ‘Bob’, ‘Jack’]
>>> L[-3:-1]
[‘Tracy’,’Bob’]#最后一个元素索引为-1
>>> L[:]
[‘Michael’, ‘Sarah’, ‘Tracy’, ‘Bob’, ‘Jack’]#复制整个序列

②更大的步长(步长不能为0)
>>> L = list(range(100))
>>> L[:10:2]
[0, 2, 4, 6, 8]#前10个数,每两个取一个
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]#所有数,每5个取一个
>>>L[8:3:-1]
[8,7,6,5,4]

3.序列相加(只能拼接同类型的序列)
>>>[1,2,3]+[4,5,6]
[1,2,3,4,5,6]

4.乘法
>>>’python’*5
‘pythonpythonpythonpythonpython’
>>>[42]*5
[42,42,42,42,42]
>>>[None]*10 #创建长度为10的列表
[None,None,None,None,None,None,None,None,None,None]

5.成员资格
>>>L=[1,2,3,4]
>>>4 in L
True

0

dict的迭代

第一种:转化为tuple

b={'1':'ni','2':'ai','3':'ni'}
for key,velue in b.items():
    print(key,':',value)
# 1 : ni
# 2 : ai
# 3 : ni

第二种:遍历
b={'1':'ni','2':'ai','3':'ni'}
for i in b:
    print(i,":",b[i])
# 1 : ni
# 2 : ai
# 3 : ni

第三种: values() 方法

b={'1':'ni','2':'ai','3':'ni'}
for i in b.values():
    print(i)
# ni
# ai
# ni

0

Python发邮件

def SendQR(picDir):
    print('准备发送二维码')
    sender = '18516528861@163.com'  #
    passWord = 'gel12345'
    mail_host = 'smtp.163.com'
    # receivers是邮件接收人,用列表保存,可以添加多个
    receivers = ['1324522527@qq.com']

    # 设置email信息
    msg = MIMEMultipart()
    # 邮件主题
    msg['Subject'] = 'WeChat QR'
    # 发送方信息
    msg['From'] = sender
    # 邮件正文是MIMEText:
    msg_content = '尽快扫码吧!'
    #简单文本到正文,plain
    msg.attach(MIMEText(msg_content, 'plain', 'utf-8'))
    #将附件图片嵌入正文,html
    msg.attach(MIMEText('<html><body><h1>尽快扫码吧!</h1>' +'<p><img src="cid:0"></p>' +'</body></html>','html','utf-8'))
    # 添加附件就是加上一个MIMEBase,从本地读取一个图片:
    with open(picDir, 'rb') as f:
        # 设置附件的MIME和文件名,这里是jpg类型,可以换png或其他类型:
        mime = MIMEBase('image', 'png', filename='QR.jpeg')
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename='QR.png')
        mime.add_header('Content-ID', '<0>')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

    # 登录并发送邮件
    try:
        # 163smtp服务器的端口号为465或
        s = smtplib.SMTP_SSL("smtp.163.com", 465)
        s.set_debuglevel(1)
        s.login(sender, passWord)
        # 给receivers列表中的联系人逐个发送邮件
        for item in receivers:
            msg['To'] = to = item
            s.sendmail(sender, to, msg.as_string())
            # print('Success!')
        s.quit()
        # print("All emails have been sent over!")
    except smtplib.SMTPException as e:
        print("Falied,%s", e)
def mail(task_name, cost_time, output_eval_file):
    hostname = get_hostname()
    message = EmailMessage()
    message['Subject'] = task_name + ' on ' + hostname + ' is over!'
    message['From'] = "18516528861@163.com"
    message['To'] = "gongel@qq.com"
    message.set_content("Task name: {}\nHost name: {}\nCost time: {}s\n".format(task_name, hostname, str(cost_time)))
    with open(output_eval_file, 'rb') as f:
        message.add_attachment(f.read(), maintype='text', subtype='plain', filename=task_name + '.txt')
    server = smtplib.SMTP("smtp.163.com")
    server.login("18516528861@163.com", "gel12345")
    server.ehlo()
    server.starttls()
    server.send_message(message)
    server.quit()

163退信的常见问题

0

Python—itchat下载拼接微信好友头像图

下载好友头像图片 getHeadImgs.py

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
import itchat
itchat.auto_login()
for friend in itchat.get_friends(update=True)[0:]:
    #可以用此句print查看好友的微信名、备注名、性别、省份、个性签名(1:男 2:女 0:性别不详)
    print(friend['NickName'],friend['RemarkName'],friend['Sex'],friend['Province'],friend['Signature'])
    img = itchat.get_head_img(userName=friend["UserName"])
    path ="C:/Users/Administrator/Documents/itchat/"+friend['NickName']+"("+friend['RemarkName']+").jpg"
    try:
        with open(path,'wb') as f:
            f.write(img)
    except Exception as e:
        print(repr(e))
itchat.run()

拼接头像图 jointHeadImgs.py

#!/usr/bin/env python3
#_*_ coding:utf-8 _*_
import os
from math import sqrt
from PIL import Image
#path是存放好友头像图的文件夹的路径
path = 'C:/Users/Administrator/Documents/itchat/'
pathList = []
for item in os.listdir(path):
    imgPath = os.path.join(path,item)
    pathList.append(imgPath)
total = len(pathList)#total是好友头像图片总数
line = int(sqrt(total))#line是拼接图片的行数(即每一行包含的图片数量)
NewImage = Image.new('RGB', (128*line,128*line))
x = y = 0
for item in pathList:
    try:
        img = Image.open(item)
        img = img.resize((128,128),Image.ANTIALIAS)
        NewImage.paste(img, (x * 128 , y * 128))
        x += 1
    except IOError:
        print("第%d行,%d列文件读取失败!IOError:%s" % (y,x,item))
        x -= 1
    if x == line:
        x = 0
        y += 1
    if (x+line*y) == line*line:
        break
NewImage.save(path+"final.jpg")

0