VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > python爬虫 >
  • python常用基础知识1

数组for循环输出,带索引:

for index, item in enumerate(name_list):
    print(index)
    print(item)

 

 

字符串查找子字符串:

beg, end 起始结束位置可选

"34123456".index("34")  # 0


"34123456".rindex("34", beg=0, end=len("34123456"))  # 4 (最后出现的位置)

参考:https://www.runoob.com/python/att-string-rindex.html

 

倒序:

1. while

复制代码
n = eval(input())
i = n
while True:
    if i == -1:
        break
    print(i)
    i -= 1
复制代码

2.for

for i in range(7,1,-1):  # 同正序一样,包头不包尾
    print(i)

参考:https://blog.csdn.net/huitinfeng/article/details/100593189

 

 

整除,取模

除法/总是返回一个浮点数,如:

>>> 6/4
1.5
>>> 2/3
0.6666666666666666

到整数的结果,丢弃分数部分,可以使用运算符 //

复制代码
>>> 6//4
1
>>> 2//3
0

# 与分母分子的数据类型有关系
>>> 6//4.0 1.0 
>>> 2.0//3 0.0


# Python3除法采取的是向下取整,即向负无穷方向取最接近精确值的整数
>>> 4//-3 -2 
>>> -10//3 -4

# 如果希望在Python3中对负数采用向零取整
>>> int(4/-3) -1 
>>> int(-10/3) -3
复制代码

采用%表示取模运算

复制代码
>>> 21%10
1
>>> 3%4
3

# 同样,负数稍有不同
>>> -21%10
9
>>> -5%4
3
复制代码

参考:https://blog.csdn.net/u012626619/article/details/80671233

 

 

 

python 中幂次方 **

1
2
3
4
5
6
7
8
>>> 5**2
25
>>> 1e-02
0.01
>>> 10e-03
0.01
>>> 2e4
20000.0

 

 

使用正则完成字符串替换:

复制代码
import re

new_y1 = 'yy1'
new_y2 = 'yy2'

template = "xxx xx{y1}x xx{y2}x xxxx"
t1 = re.sub(r'\{y1\}', new_y1, template, 0, re.M)  # 0  替换次数全部替换   re.M 多行匹配,影响 ^ 和 $

t2 = re.sub(r'\{y2\}', new_y2, t1, 0, re.M)
复制代码

 字符串格式化:https://www.runoob.com/python/att-string-format.html

 

运行时间计时

复制代码
# 装饰器,计算运行的时间
def timer(func):
    def decor(*args):
        start_time = time.time()
        func(*args)
        end_time = time.time()
        d_time = end_time - start_time
        print("the running time is : ", d_time)

    return decor


# 需要被计时的函数
@timer
def xxx():
   time.sleep(2)
复制代码

 

 

保留2位小数

复制代码
def get_n_float(f_str, n):
    # f_str 为待处理的数,n为要保留的位数,保留时不做四舍五入
    f_str = str(f_str)
    a, b, c = f_str.partition('.')  # a为整数部分,b为. ,c为小数部分
    c = (c + "0"*n)[:n]  #位数不足时补0
    return ".".join([a, c])
复制代码

 

 

 

pymysql查询出的数据为元组

例如:

1
2
3
4
5
6
7
>>> res = ((1'aa'), (2'bb'), (3'cc'))
 
# 要转化为字典的话
 
>>> dict(res)
 
{1'aa'2'bb'3'cc'}

要交互key,value的话

1
2
3
4
5
6
7
8
9
10
11
12
13
res = ((1'aa'), (2'bb'), (3'cc'))
keys = []
values = []
 
for in range(len(res)):
    keys.append(res[c][0])
    values.append(res[c][1])
 
res_dict = dict(zip(values, keys))
print(res_dict)
 
# 结果为
{'aa'1'bb'2'cc'3}

 

 

copy

直接赋值时,新变量只是前一变量的引用。新变量改变了,前一变量也会改变。

浅拷贝只拷贝父对象,不拷贝子对象。如下offline_json_record的time为父对象,tags为子对象。任意一个变量中的子对象改变了,其他变量中的子对象也会同时改变。

深拷贝完全拷贝了父对象与子对象。变量中的父、子对象改变后,与被拷贝的变量相互不影响。如下offline_json_record,r1,r2相互不影响。

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import copy
 
 
offline_json_record = {
    "measurement"'offline_device',
    "time": '',
    "tags": {
        'region': ''
    },
    "fields": {
        'value'0
    }
}
 
r1 = copy.deepcopy(offline_json_record)
r2 = copy.deepcopy(offline_json_record)

 

参考:

https://www.runoob.com/w3cnote/python-understanding-dict-copy-shallow-or-deep.html 

 

 

当前年月日

1
2
3
4
5
6
7
8
9
>>> import datetime
>>> datetime.datetime.now().year
2020
 
>>> datetime.datetime.now().month
10
 
>>> datetime.datetime.now().day
8

 

 参考:

https://www.runoob.com/python/python-date-time.html

https://blog.csdn.net/hanyuyang19940104/article/details/84069720

 

 

timestamp与datetime转化

1
2
3
4
5
6
7
8
9
10
11
12
import time
import datetime
 
 
timestamp = time.time()
= datetime.datetime.fromtimestamp(timestamp)
 
d2 = datetime.datetime.now()
timestamp2 = time.mktime(d2.timetuple())
 
# 常用datetime格式化  2020-10-15 11:47:09
d3_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

 

 

filter返回列表中满足条件的元素

1
2
3
4
5
6
7
offline_list = list(filter(lambda r: r['status'== "OFFLINE", all_list))
 
# 等同于
def is_offline(record):
    return record['status'== "OFFLINE"
 
offline_list = list(filter(is_offline, all_list))

 

 

 

python内置函数:

https://blog.csdn.net/weixin_30332241/article/details/97496902?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~all~sobaiduend~default-1-97496902.nonecase&utm_term=python%E6%80%8E%E4%B9%88%E8%A1%A8%E7%A4%BA10%E7%9A%84n%E6%AC%A1%E6%96%B9&spm=1000.2123.3001.4430

 

 

使用session保持登录

复制代码
    import requests
    import json
    

    url = "http://xxx.com"
    
    hd = {
        'Cookie': 'xxxx'
         }

    data = {'d1': 'xx',
            'd2': "xxx"
            }
    # res = requests.post(url, data=data)
    session = requests.Session()
    session.headers = hd
    res = session.post(url, data=data)

    resp_json = json.loads(res.text)
复制代码

 

 

获取当期日期时间

import datetime


# 当期时间 2021-02-18 18:08:32
create_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

 

 

list中取出某个键的值

复制代码
                    tl_res_obj_list = tl_json_str['data']['list']  # 获取list
                        for index0, item0 in enumerate(tl_res_obj_list):
                            try:
                                item0['xxx']  # 该项才有xxx
                                w[21] = item0['createTime']  # 时间
                                break
                            except:
                                continue
                        if not w[21]:
                            w[21] = ''
复制代码

 

 

分页处理

复制代码
'''处理分页默认每页10条'''
            total_size = int(json_str['data']['totalSize'])
            if total_size > 10:
                total_page = math.ceil(total_size / 10)  # 向上取整 2.1 -> 3
                for curpage in range(2, total_page + 1):
                    self.get_list_by_curpage(day, curpage=curpage, success_cnt=success_cnt)
复制代码

 

随机等待n分钟

    minutes = random.uniform(0.5, 21.5)  # 生成float随机值
    print('等待{}分钟'.format(minutes))
    time.sleep(minutes * 60)

 

出处:https://www.cnblogs.com/ycc1/p/python001.html


相关教程