python(day027——集合、时间、类)

1.集合

可变集合set和不可变集合frozenset。

会过滤掉重复内容。set内元素没有顺序,不能用坐标取值。

>>> a=set("hello")
>>> a
{'o', 'e', 'l', 'h'}
>>> set((1,2,3))
{1, 2, 3}
>>> a.add("abc")  #集合的增加
>>> a
{'h', 'o', 'e', 'abc', 'l'}
>>> a.update("abc")   #集合的增加
>>> a
{'h', 'c', 'o', 'e', 'a', 'abc', 'b', 'l'}
#遍历集合的元素
>>> for i in a:print(i)
...
h
c
o
e
a
abc
b
l
#集合的删除
>>> a.remove("abc")
>>> a
{'h', 'c', 'o', 'e', 'a', 'b', 'l'}
>>> a.discard("efgd")
#discard:如果存在则删除;如果没找到,则什么也不做。该函数没有返回值

#pop:删除并返回集合s中的第一个元素,如果为空引发KeyError错误
>>> a
{'f', 'e', 'a', 'c', 'g', 'b'}
>>> a.pop()
'f'
>>> a
{'e', 'a', 'c', 'g', 'b'}
>>> len(a)
5
>>> n=a.copy()
>>> n
{'g', 'b', 'e', 'a', 'c'}
>>> n.clear()
>>> n
set()

>>> b=frozenset([1,2,2,3])
>>> b
frozenset({1, 2, 3})
>>> type(b)
<class 'frozenset'>
>>> b.add("1")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'

2.集合的交集、并集、差集

>>> a&b
{'d', 'c'}
>>> a|b
{'d', 'c', 'e', 'a', 'b', 'f'}
>>> a-b
{'a', 'b'}
>>> b-a
{'e', 'f'}
a="I am a boy"
b="I am 18 years old"
#1.求两句中一共出现了多少个单词
#2.求两句中相同单词的个数
#3.不同单词的个数
l1=a.split()
l2=b.split()
l=l1+l2
s=set(l1)
s=s.update(s)
s2=set(l1)&set(l2)
s3=set(l1)|set(l2)
s3=s3-s2
print(s)
print(s2)
print(s3)
a="I am a good boy"
b="She is a good girl"
#求两句话中重复单词和不重复单词
lista=a.split()
listb=b.split()
seta=set(lista)
setb=set(listb)
print("重复单词:",setb&seta)
print("不重复单词:",(seta|setb)-(setb&seta))

 


3.时间

>>> import time
>>> time.time()
1596018091.3119504
>>> t1=time.time()
>>> t2=time.time()
>>> t2-t1 #时间差
3.593512773513794
#时间元组,tm_wday表示星期,星期一是0
>>> time.localtime()
time.struct_time(tm_year=2020, tm_mon=7, tm_mday=29, tm_hour=18, tm_min=25, tm_sec=16, tm_wday=2, tm_yday=211, tm_isdst=0)
>>> t=time.localtime()
>>> list=[]
>>> for i in t:
...     list.append(str(i))
...
>>> list[0]+"年"+list[1]+"月"+list[2]+"日"+" "+list[3]+"时"+list[4]+"分"+list[5]+"秒"
'2020年7月29日 18时30分1秒'
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2020-07-29 18:41:43'
>>> import locale
>>> locale.setlocale(locale.LC_CTYPE,"chinese")
'Chinese_China.936'
>>> strTime=time.strftime("%Y年%m月%d日 %H:%M:%S",time.localtime())
>>> strTime
'2020年07月29日 18:45:50'

 strptime()方法:根据指定的格式把一个时间字符串解析为时间元组。

>>> a=time.localtime()
>>> a
time.struct_time(tm_year=2020, tm_mon=8, tm_mday=1, tm_hour=22, tm_min=48,
 tm_sec=32, tm_wday=5, tm_yday=214, tm_isdst=0)
>>> time.mktime(a)  #转化为时间戳
1596293312.0
两个日期相减的时间差:
import datetime

#求两个日期间的天数差
d1 = (datetime.datetime(2015, 7, 5))
d2 = (datetime.datetime(2015, 8, 26))
print ((d2 - d1).days)


计算日期:
#coding=utf-8
from datetime import datetime
from datetime import timedelta

now = datetime.now()
#设置100天前的时间间隔
delta = timedelta(days = -100)
#得到100天前的时间
oldTime = now + delta
print (oldTime.strftime("%Y-%m-%d"))
import time
import datetime
import locale


class TimeUtil:

    def __init__(self, curtime=None):
        self.curtime = curtime

    def get_timestemp(self):
        return time.time()

    def get_date(self):
        return time.strftime("%Y-%m-%d")

    def get_time(self):
        return time.strftime("%H:%M:%S")

    def get_datetime(self):
        return time.strftime("%Y-%m-%d %H:%M:%S")

    def get_chinesedate(self):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
        strTime = time.strftime("%Y年%m月%d日", time.localtime())
        return strTime

    def get_chinesetime(self):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
        strTime = time.strftime("%H时%M分%S秒", time.localtime())
        return strTime

    def get_chinesedatetime(self):
        locale.setlocale(locale.LC_CTYPE, 'chinese')
        strTime = time.strftime("%Y年%m月%d日%H时%M分%S秒", time.localtime())
        return strTime

    def compute_date(self, day_interval):
        # 获取今天的日期
        today = datetime.date.today()
        # 在今天的日期上再减10天
        if isinstance(day_interval, int) and day_interval >= 0:
            return today + datetime.timedelta(days=day_interval)
        elif isinstance(day_interval, int) and day_interval < 0:
            return today - datetime.timedelta(days=abs(day_interval))

    def timestamp_to_date(self, timestamp):
        if not isinstance(timestamp, (int, float)):
            return None
        locale.setlocale(locale.LC_CTYPE, 'chinese')
        time_tuple = time.localtime(timestamp)

        return str(time_tuple[0]) + "年" + str(time_tuple[1]) + "月" + str(time_tuple[2]) + "日"

    def timestamp_to_time(self,timestamp):
        if not isinstance(timestamp,(int,float)):
            return None
        locale.setlocale(locale.LC_CTYPE, 'chinese')
        time_tuple = time.localtime(timestamp)
        return str(time_tuple[3])+"时"+str(time_tuple[4])+"分"+str(time_tuple[5])+"秒"

    def timestamp_to_datetime(self,timestamp):
        return self.timestamp_to_date(timestamp)+self.timestamp_to_time(timestamp)

if __name__ == "__main__":
    t = TimeUtil()
    print(t.get_timestemp())
    print(t.get_date())
    print(t.get_time())
    print(t.get_datetime())
    print(t.get_chinesedate())
    print(t.get_chinesetime())
    print(t.get_chinesedatetime())
    print(t.compute_date(10))
    print(t.timestamp_to_date(2017389293))
    print(t.timestamp_to_time(8737492939))
    print(t.timestamp_to_datetime(2137492992))

 

4.类

>>> class Brid:
...   def  __init__(self,length,height,color):
...     self.length=length
...     self.height=height
...     self.color=color
...
>>> b=Brid(10,20,"red")
>>> d=Brid(10,20,"yellow")
>>> b
<__main__.Brid object at 0x000001BF33FFDC48>
>>> d
<__main__.Brid object at 0x000001BF33FFDE48>
>>> b.color
'red'
>>> d.color
'yellow'
#类的定义在内存中某个地址存储,且只有一份
#类变量在类的定义中储存,且只有一份
class Brid:
    count=0  #类变量
    #构造方法:主要设定实例中的参数
    def  __init__(self,length,height,color):
        self.length = length
        self.height = height
        self.color = color
        Brid.count+=1 #统计生成了多少个实例

    #实例方法
    def get_color(self): 
        return self.color

b=Brid(10,20,"red")
print(b.color)
print(b.get_color())#python调用实例方法时候,会自动给你传实例给方法

c=Brid(15,15,"black")
print(c.color)
print(c.get_color())

#b和c在内存中式各自独立保存,互不影响
c.color="yellow"
print(c.get_color())
print(b.get_color())

print(id(c))
print(id(b))

'''原理:
方法:类里面定义的函数
函数:类外面定义的函数
类(类变量,方法):在内存中只有一个地方存储,那么类中定义的方法也在那个地方存储。
当实例想调用某个类中定义的方法时,需要把实例对象传递给类中定义的方法,才能够使用。
python默认吧实例地址自动传递给方法中的self,这样就可以找到不同实例中的实例变量。
'''
print(Brid.count)#类变量

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值