Python常用知识点整理

432 阅读3分钟

1. 获取list中的下标及数据

num_list = [1]
for k,v in list(enumerate(num_list)):    
    print(k,v)
# 结果:0 1

2. 获取两个list的交集和差集

 交集

# 方法一
a = [2,3,4]
b = [3,4,5,6]
print(list(set(a).intersection(set(b))))
# 结果:[3, 4]

# 方法二
print(list(set(a) & set(b)))
# 结果:[3, 4]

  差集

# 方法一
print(list(set(a).difference(set(b))))  # a中有而b中没有的# 结果:[2]
# 方法二
print(list(set(a) - set(b)))  # a中有而b中没有的# 结果:[2]

3. md5加密

  英文

import hashlib
hashlib.new('md5',b'123456').hexdigest()
# 结果:e10adc3949ba59abbe56e057f20f883e

  中文

import hashlib
string = '你好'
hashlib.md5(string.encode(encoding='utf-8')).hexdigest()
# 结果:7eca689f0d3389d9dea66ae112e5cfd7

4. 日期、时间戳

  日期

from datetime import (datetime, timedelta)

current_datetime = datetime.now()  # 返回系统当前时间: 2020-06-10 15:28:34.184488
current_date = datetime.now().date()  # 返回当前时间的日期: 2020-06-10
current_hms = datetime.now().time()  # 返回当前时间的时分秒: 15:28:34.184488
current_ctime = datetime.now().ctime()  # 返回当前含英文、星期的时间: Wed Jun 10 15:28:34 2020
current_year = datetime.now().year  # 返回当前时间的年份: 2020
current_month = datetime.now().month  # 返回当前时间的月份: 6
current_day = datetime.now().day  # 返回当前时间的日期: 10
current_hour = datetime.now().hour  # 返回当前时间的小时: 15
current_minute = datetime.now().minute  # 返回当前时间的分钟: 28
current_second = datetime.now().second  # 返回当前时间的秒数: 34

current_str_datetime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 返回当前字符串的时间: '2020-06-10 16:31:22'
yesterday_str_datetime = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')  # 返回昨天当前字符串的时间: '2020-06-09 16:31:22'

  时间戳

import time

def date_to_timestamp(date):
    """日期格式转换为时间戳"""
    data_sj = time.strptime(date, "%Y-%m-%d %H:%M:%S")
    int_timestamp = int(time.mktime(data_sj))
    return int_timestamp

def timestamp_to_date(timestamp):
    """时间戳转换为日期格式"""
    data_sj = time.localtime(timestamp)
    str_date = time.strftime("%Y-%m-%d %H:%M:%S",data_sj)
    return str_date

timestamp = date_to_timestamp('2020-06-10 00:00:00')
print('日期转换为时间戳: ', timestamp)  # 日期转换为时间戳:  1591718400
date = timestamp_to_date(1591718400)
print('时间戳转换为常规日期: ', date)  # 时间戳转换为常规日期:  2020-06-10 00:00:00

5. 三目操作符

1 == 1 and 2 or 3   # 返回2
# 等同于
2 if 1 == 1 else 3  # 返回2

6. 列表碾平式

 需求:将嵌套list转换为不嵌套list

test_list = [[1,2],[3,4]]
1. from itertools import chain
   list(chain.from_iterable(test_list))
   结果:[1, 2, 3, 4]

2. from itertools import chain
   list(chain(*test_list))
   结果:[1, 2, 3, 4]

3. sum(test_list, [])
   结果:[1, 2, 3, 4]

4. [x for y in test_list for x in y]
   结果:[1, 2, 3, 4]

5. 万能方法(递归,支持结构嵌套不一致的情况)
   test_list = [[1,2],[3,[4,5]]]
   func = lambda x: [y for t in x for y in func(t)] if type(x) is list else [x]
   func(test_list)
   结果:[1, 2, 3, 4, 5]

7. 列表推导式

 需求:将list中的每一项都加1

# good
test_list = [1,2,3]
new_list = [x+1 for x in test_list]
# bad
def add_list(test_list):
    tmp_list = []
    for x in test_list:
      tmp_list.append(x+1)
new_list = add_list(test_list)
# 结果:[2,3,4]

8. vars()用法

 需求:打印参数

def func(a, b, c):
    print(vars())
func(1, 2, 3)
# 结果:{'c': 3, 'b': 2, 'a': 1}

9. 列表字典中的字段排序

sort_list = [{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]
sorted_list = sorted(sort_list, key=lambda sort_list : sort_list['age'], reverse=False)  
# reverse: False 升序 True 降序

10. 去除数字后面多余的0

num = 0.1230
num = '%g' % (num)
# 结果:0.123