python常用语法点

AbrahamW

关注

阅读 97

2022-03-17

python常用语法点

1.with as 语句中调用构造函数不同写法的总结

with as 简介

有一些操作可能需要事先设置,事后做清理工作。对于这种场景,python 的with 语法提供了一种非常方便的处理方式。
例如:

  with open('test.txt') as f:
    data = f.read()

相当于try finally 代码:

f = open('test.txt')
try:
  data = f.read()
finally:
  f.close()

with as 语句中调用构造函数

使用with as 时,可以在with as 语句中调用构造函数,也可以在之前调用,具体有什么区别,代码实例如下:
!!!含难呀

2.时间戳转化为指定日期格式

strftime(format,time):得到format格式控制下的一个代表时间的字符串。(string from time–>strftime)
strptime(date_string,format):根据format从字符串创建出一个时间类的对象。(string produce time)
date,datetime,time对象都支持上述两个函数。
方法一:

import time
# 将时间戳转换为指定格式日期
# 获取当时间戳
now = int(time.time())
# now = 1639597800
# 转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S"
timeArray = time.localtime(now)
otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S",timeArray)
print(otherStyleTime)
#结果:
2021-12-16 03:50:00

方法二:

import datetime
# 获取当前时间
now = datetime.datetime.now()
otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
print(otherStyleTime)
#结果:
2022-03-01 16:33:43

3.带有时区的日期数据转换为时间戳

import time
import datetime
now = '2021-12-16 03:50:51.648199+00:00'
new_date = time.strptime(now,'%Y-%m-%d %H:%M:%S.%f%z')
stamp = int(time.mktime(new_date))
print(stamp)
#结果:
time.struct_time(tm_year=2021, tm_mon=12, tm_mday=16, tm_hour=3, tm_min=50, tm_sec=51, tm_wday=3, tm_yday=350, tm_isdst=-1)
1639597851

4.python中利用all()来优化减少判断的代码

情景:如果我有一个list,想判断其中的元素是否满足一个条件,后面的元素大于等于前面元素。下面介绍一般的写法和通过all()来进行比较的写法。
test = [1, 2, 3, 4, 5, 4]
一、一般写法

def checker(test):
  for i in range(len(test)):
    if i+1 < len(test):
      if test[i] > test[i+1]:
        return False
  return True

二、使用all()和zip()的写法
all() : 函数用于判断给定的可迭代参数iterable中的所有元素是否都为True,如果是返回True,否则返回False。如果可迭代参数为空,返回True
zip() : 是函数用于将可迭代对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象

def checker_two(test):
  return all(i <= j for i,j in zip(test,test[1:]))

# 如果不想zip的第二个参数创建一个list,可以这样写
from itertools import  islice
def checker_three(test):
  return all(i <= j for i, j in zip(test, islice(test, 1, None)))

"""
zip(*iterables) --> 一个 zip 对象产生的元组,直到输入用尽。  
       >>> list(zip('abcdefg', range(3), range(4)))
       [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
     zip 对象产生 n 长度的元组,其中 n 是可迭代的数量
     作为位置参数传递给 zip()。 每个元组中的第 i 个元素
     来自 zip() 的第 i 个可迭代参数。 这种情况一直持续到
     最短的参数已用尽。
    
  islice(iterable, stop) --> islice 对象
  islice(iterable, start, stop[, step]) --> islice 对象
     返回一个迭代器,其 next() 方法从
     可迭代对象中返回一个被选中的值。 如果指定了 start,将跳过所有前面的元素;
     否则, start 默认为零。 步幅默认为一。 如果
     指定为另一个值, step 确定有多少个值
     在连续呼叫之间跳过。 像列表中的 slice() 一样工作
     但返回一个迭代器。
"""

python3 中zip()的使用

a = [1, 2, 3]
b = [4, 5, 6]
zipped = zip(a, b)
print(zipped)  # 返回的是一个对象
print(list(zipped))  # 使用list()将对象转换为列表
#结果:
<zip object at 0x11b6c4b40>
[(1, 4), (2, 5), (3, 6)]

5. python 中的NoneType 和空值如何判断

即(TypeError:object of type ‘NoneType’ has no len())
NoneType和 空值是不一样的,可以理解为Nonetype为不存在这个参数,空值表示参数存在,但值为空。

if test is None:
print("test is NoneTyep")
elif test:
print("test is not null")
else:
print("test is null")

精彩评论(0)

0 0 举报