Python (100例)(一)

基础62例

1.十进制转二进制

bin(10)
'0b1010'

2.十进制转八进制

oct(9)
'0o11'

3.十进制转十六进制

hex(15)
'0xf'

4.字符串转字节

s='apple'
bytes(s,encoding='utf-8')
b'apple'

==UTF-8是一种变长字节编码方式。对于某一个字符的UTF-8编码,如果只有一个字节则其最高二进制位为0;如果是多字节,其第一个字节从最高位开始,连续的二进制位值为1的个数决定了其编码的位数,其余各字节均以10开头。UTF-8最多可用到6个字节。 ==

5.字符类型、数值型等转为字符串类型

i=100
str(i)
'100'

6.十进制数所对应得ASCII字符

chr(65)
'A'

7.ASCII字符转十进制数

ord('A')
65

8.转为字典
创建数据字典的几种方式

>>>dict()
{}
>>>dict(a='a',b='b')
{'a':'a','b'='b'}
>>>dict(zip(['a','b'],[1,2]))
{'a':1,'b':2}
>>>dict([('a',1),('b',2)])
{'a':1,'b':2}

9.转为浮点类型
整数或数值型字符串转换为浮点数:

float(3)
3.0

如果不能转化为浮点数,则会报ValueError:

float('a')
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    float('a')
ValueError: could not convert string to float: 'a'入代码片

10.转为整型
int(x, base =10)
x 可能为字符串或数值,将 x 转换为整数。
base为进制。
如果参数是字符串,那么它可能包含符号和小数点。如果超出普通整数的表示范围,一个长整数被返回

int('12',16)
18

11.转为集合
返回一个 set 对象,集合内不允许有重复元素:

a=[1,4,2,3,1]
set(a)
{1,2,3,4}

12.转为切片
class slice(start, stop[, step])
返回一个由 range(start, stop, step) 指定索引集的 slice 对象,代码可读性变好。

a = [1,4,2,3,1]
my_slice = slice(0,5,2)
a[my_slice]
[1, 2, 1]

13.转元组
tuple() 将对象转为一个不可变的序列类型

a=[1,3,5]
a.append(7)
a
[1, 3, 5, 7]
#禁止a增删元素,只需转为元组
t=tuple(a)
t
(1, 3, 5, 7)

14.转冻结集合
创建不可修改的集合:

a = frozenset([1,1,3,2,3])
a # a 无 pop,append,insert等方法
frozenset({1, 2, 3})

15.商和余数

divmod(10,3)
(3,1)

16.幂和余同时做
pow三个参数都给出表示先幂运算再取余:

pow(3,2,4)
1

17.四舍五入
四舍五入,ndigits代表小数点后保留几位:

round(10.044,2)
10.04
round(10.046,2)
10.05

18.查看变量所占字节数

import sys
a = {'a':1,'b':2.0}
sys.getsizeof(a) # 变量占用字节数
240

19.门牌号
返回对象的内存地址

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name
          
>>> xiaoming = Student('001','xiaoming') 
>>> id(xiaoming)
2281930739080

20.排序函数

>>> a = [1,4,2,3,1]
#降序
>>> sorted(a,reverse=True)
[4, 3, 2, 1, 1]
>>> a = [{'name':'xiaoming','age':18,'gender':'male'},
       {'name':'xiaohong','age':20,'gender':'female'}]
#按 age升序
>>> sorted(a,key=lambda x: x['age'],reverse=False)
[{'name': 'xiaoming', 'age': 18, 'gender': 'male'}, 
{'name': 'xiaohong', 'age': 20, 'gender': 'female'}]

21.求和函数

>>> a = [1,4,2,3,1]
>>> sum(a)
11
#求和初始值为1
>>> sum(a,1)
12

22.计算表达式
计算字符串型表达式的值”

s="1+3+5"
eval(s)
9
eval('[1,3,5]*3')
[1,3,5,1,3,5,1,3,5]

23.真假

>>> bool(0)
False
>>> bool(False)
False
>>> bool(None)
False
>>> bool([])
False
>>> bool([False])
True
>>> bool([0,0,0])
True

24.都为真
如果可迭代对象的所有元素都为真,那么返回 True,否则返回False

#有0,所以不是所有元素都为真
>>> all([1,0,3,6])
False
#所有元素都为真
>>> all([1,2,3])
True

25.至少一个为真
接受一个可迭代对象,如果可迭代对象里至少有一个元素为真,那么返回True,否则返回False

# 没有一个元素为真
>>> any([0,0,0,[]])
False
# 至少一个元素为真
>>> any([0,0,1])
True

26.获取用户输入内容

>>> input()
I'm typing 
"I'm typing "

27.print用法

>>> lst = [1,3,5]
# f 打印
>>> print(f'lst: {lst}')
lst: [1, 3, 5]
# format 打印
>>> print('lst:{}'.format(lst))
lst:[1, 3, 5]

28.字符串格式化
格式化字符串常见用法:

>>> print("i am {0},age {1}".format("tom",18))
i am tom,age 18
>>> print("{:.2f}".format(3.1415926)) # 保留小数点后两位
3.14
>>> print("{:+.2f}".format(-1)) # 带符号保留小数点后两位
-1.00
>>> print("{:.0f}".format(2.718)) # 不带小数位
3
>>> print("{:0>3d}".format(5)) # 整数补零,填充左边, 宽度为3
005
>>> print("{:,}".format(10241024)) # 以逗号分隔的数字格式
10,241,024
>>> print("{:.2%}".format(0.718)) # 百分比格式
71.80%
>>> print("{:.2e}".format(10241024)) # 指数记法
1.02e+07

29.返回对象哈希值
返回对象的哈希值。值得注意,自定义的实例都可哈希:

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name
        
>>> xiaoming = Student('001','xiaoming')
>>> hash(xiaoming)
-9223371894234104688

list, dict, set等可变对象都不可哈希(unhashable):

>>> hash([1,3,5])
Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    hash([1,3,5])
TypeError: unhashable type: 'list'

30.打开文件
返回文件对象:

>>> import os
>>> os.chdir('D:/source/dataset')
>>> os.listdir()
['drinksbycountry.csv', 'IMDB-Movie-Data.csv', 'movietweetings', 
'titanic_eda_data.csv', 'titanic_train_data.csv']
>>> o = open('drinksbycountry.csv',mode='r',encoding='utf-8')
>>> o.read()
"country,beer_servings,spirit_servings,wine_servings,total_litres_of_pur
e_alcohol,continent\nAfghanistan,0,0,0,0.0,Asia\nAlbania,89,132,54,4.9,"

mode取值表:
在这里插入图片描述
31.查看对象类型
class type(name,bases,dict)
传入参数,返回object类型:

>>> type({4,6,1})
<class 'set'>
>>> type({'a':[1,2,3],'b':[4,5,6]})
<class 'dict'>
>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name

>>> type(Student('1','xiaoming'))
<class '__main__.Student'>

32.两种创建属性的方式
返回property属性,典型的用法:

>>> type({4,6,1})
<class 'set'>
>>> type({'a':[1,2,3],'b':[4,5,6]})
<class 'dict'>
>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name

>>> type(Student('1','xiaoming'))
<class '__main__.Student'>

使用C类:

>>> C().x=1
>>> c=C()
# 属性x赋值
>>> c.x=1
# 拿值
>>> c.getx()
1
# 删除属性x
>>> c.delx()
# 再拿报错
>>> c.getx()
Traceback (most recent call last):
  File "<pyshell#118>", line 1, in <module>
    c.getx()
  File "<pyshell#112>", line 5, in getx
    return self._x
AttributeError: 'C' object has no attribute '_x'
# 再属性赋值
>>> c.x=1
>>> c.setx(1)
>>> c.getx()
1

使用@property装饰器,实现与上完全一样的效果:

class C:
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

33.是否可调用
判断对象是否可被调用,能被调用的对象是一个callable 对象。

>>> callable(str)
True
>>> callable(int)
True

Student 对象实例目前不可调用:

>>> class Student():
        def __init__(self,id,name):
            self.id = id
            self.name = name

>>> xiaoming = Student(id='1',name='xiaoming')
>>> callable(xiaoming)
False

如果 xiaoming能被调用 , 需要重写Student类的__call__方法:

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name

此时调用 xiaoming():

>>> xiaoming = Student('001','xiaoming')
>>> xiaoming()
I can be called
my name is xiaoming

34.动态删除属性
删除对象的属性:

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name

>>> xiaoming = Student('001','xiaoming')
>>> delattr(xiaoming,'id')
>>> hasattr(xiaoming,'id')
False

35.动态获取对象属性
获取对象的属性:

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name
       
>>> xiaoming = Student('001','xiaoming')
>>> getattr(xiaoming,'name') # 获取name的属性值
'xiaoming'

36.对象是否有某个属性

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name
        
>>> xiaoming = Student('001','xiaoming')        
>>> getattr(xiaoming,'name')# 判断 xiaoming有无 name属性
'xiaoming'
>>> hasattr(xiaoming,'name')
True
>>> hasattr(xiaoming,'address')
False

37.isinstance
判断object是否为classinfo的实例,是返回true:

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name
       
>>> xiaoming = Student('001','xiaoming')
>>> isinstance(xiaoming,Student)
True

38.父子关系鉴定

使用 issubclass 判断:

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name
        
>>> class Undergraduate(Student): 
       pass
        
# 判断 Undergraduate 类是否为 Student 的子类 
>>> issubclass(Undergraduate,Student)
True

第二个参数可为元组:

issubclass(int,(int,float))
True

39.所有对象之根
object 是所有类的基类

>>> isinstance(1,object)
True

>>> isinstance([],object)
True

40.一键查看对象所有方法
不带参数时返回当前范围内的变量、方法和定义的类型列表;带参数时返回参数的属性,方法列表。

>>> class Student():
      def __init__(self,id,name):
        self.id = id
        self.name = name

>>> xiaoming = Student('001','xiaoming')
>>> dir(xiaoming)
['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'id', 'name']

41.枚举对象
Python的枚举对象

>>> s = ["a","b","c"]
>>> for i,v in enumerate(s):
       print(i,v)
0 a
1 b
2 c

43.创建迭代器

>>> class TestIter():
 def __init__(self,lst):
  self.lst = lst
  
 # 重写可迭代协议__iter__
 def __iter__(self):
  print('__iter__ is called')
  return iter(self.lst)

迭代 TestIter 类:

>>> t = TestIter()
>>> t = TestIter([1,3,5,7,9])
>>> for e in t:
 print(e)

 
__iter__ is called
1
3
5
7
9

43.创建range迭代器

  1. range(stop)
  2. range(start, stop[,step])
    生成一个不可变序列的迭代器:
>>> t = range(11)
>>> t = range(0,11,2)
>>> for e in t:
     print(e)

0
2
4
6
8
10

44.反向

>>> rev = reversed([1,4,2,3,1])
>>> for i in rev:
 print(i)
 
1
3
2
4
1

45.打包

>>> x = [3,2,1]
>>> y = [4,5,6]
>>> list(zip(y,x))
[(4, 3), (5, 2), (6, 1)]
>>> for i,j in zip(y,x):
 print(i,j)

4 3
5 2
6 1

46.过滤器
函数通过 lambda 表达式设定过滤条件,保留 lambda 表达式为True的元素:

>>> fil = filter(lambda x: x>10,[1,11,2,45,7,6,13])
>>> for e in fil:
       print(e)

11
45
13

47.链式比较

>>> i = 3
>>> 1 < i < 3
False
>>> 1 < i <=3
True

48.链式操作

>>> from operator import (add, sub)
>>> def add_or_sub(a, b, oper):
 return (add if oper == '+' else sub)(a, b)
>>> add_or_sub(1, 2, '-')
-1

49.split 分割

>>> 'i love python'.split(' ')
['i', 'love', 'python']

50.replace替换

>>> 'i\tlove\tpython'.replace('\t',',')
'i,love,python'

51.反转字符串

>>> st="python"
>>> ''.join(reversed(st))
'nohtyp'

在这里插入图片描述
52.使用time模块打印当前时间

# 导入time模块
>>> import time
# 打印当前时间,返回浮点数
>>> seconds = time.time()
>>> seconds
1588858156.6146255

53.浮点数转时间结构体

# 浮点数转时间结构体
>>> local_time = time.localtime(seconds)
>>> local_time
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=7, tm_hour=21, tm_min=29, tm_sec=16, tm_wday=3, tm_yday=128, tm_isdst=0)
  • tm_year: 年
  • tm_mon: 月
  • tm_mday: 日
  • tm_hour: 小时
  • tm_min:分
  • tm_sec: 分
  • tm_sec: 秒
  • tm_wday: 一周中索引([0,6], 周一的索引:0)
  • tm_yday: 一年中索引([1,366])
  • tm_isdst: 1 if summer time is in effect, 0 if not, and -1 if unknown
    54.时间结构体转时间字符串
# 时间结构体转时间字符串
>>> str_time = time.asctime(local_time)
>>> str_time
'Thu May  7 21:29:16 2020'

55.时间结构体转指定格式时间字符串

# 时间结构体转指定格式的时间字符串
>>> format_time = time.strftime('%Y.%m.%d %H:%M:%S',local_time)
>>> format_time
'2020.05.07 21:29:16'

56.时间字符串转时间结构体

# 时间字符串转时间结构体
>>> time.strptime(format_time,'%Y.%m.%d %H:%M:%S')
time.struct_time(tm_year=2020, tm_mon=5, tm_mday=7, tm_hour=21, tm_min=29, tm_sec=16, tm_wday=3, tm_yday=128, tm_isdst=-1)

57.年的日历图

>>> import calendar
>>> from datetime import date
>>> mydate=date.today()
>>> calendar.calendar(2020)

结果:

                                  2020

      January                   February                   March        
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                      1  2                         1
 6  7  8  9 10 11 12       3  4  5  6  7  8  9       2  3  4  5  6  7  8
13 14 15 16 17 18 19      10 11 12 13 14 15 16       9 10 11 12 13 14 15
20 21 22 23 24 25 26      17 18 19 20 21 22 23      16 17 18 19 20 21 22
27 28 29 30 31            24 25 26 27 28 29         23 24 25 26 27 28 29
                                                    30 31

       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                   1  2  3       1  2  3  4  5  6  7
 6  7  8  9 10 11 12       4  5  6  7  8  9 10       8  9 10 11 12 13 14
13 14 15 16 17 18 19      11 12 13 14 15 16 17      15 16 17 18 19 20 21
20 21 22 23 24 25 26      18 19 20 21 22 23 24      22 23 24 25 26 27 28
27 28 29 30               25 26 27 28 29 30 31      29 30

        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                      1  2          1  2  3  4  5  6
 6  7  8  9 10 11 12       3  4  5  6  7  8  9       7  8  9 10 11 12 13
13 14 15 16 17 18 19      10 11 12 13 14 15 16      14 15 16 17 18 19 20
20 21 22 23 24 25 26      17 18 19 20 21 22 23      21 22 23 24 25 26 27
27 28 29 30 31            24 25 26 27 28 29 30      28 29 30
                          31

      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
          1  2  3  4                         1          1  2  3  4  5  6
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       7  8  9 10 11 12 13
12 13 14 15 16 17 18       9 10 11 12 13 14 15      14 15 16 17 18 19 20
19 20 21 22 23 24 25      16 17 18 19 20 21 22      21 22 23 24 25 26 27
26 27 28 29 30 31         23 24 25 26 27 28 29      28 29 30 31
                          30

58.月的日历图

>>> import calendar
>>> from datetime import date
>>> mydate = date.today()
>>> calendar.month(mydate.year, mydate.month)

结果:

      May 2020
Mo Tu We Th Fr Sa Su
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

59.判断是否为闰年

>>> import calendar
>>> from datetime import date
>>> mydate = date.today()
>>> is_leap = calendar.isleap(mydate.year)
>>> ("{}是闰年" if is_leap else "{}不是闰年\n").format(mydate.year)
'2020是闰年'

60.with读写文件
读文件:

>> import os
>>> os.chdir('D:/source/dataset')
>>> os.listdir()
['drinksbycountry.csv', 'IMDB-Movie-Data.csv', 'movietweetings', 'test.csv', 'titanic_eda_data.csv', 'titanic_train_data.csv', 'train.csv']
# 读文件
>>> with open('drinksbycountry.csv',mode='r',encoding='utf-8') as f:
      o = f.read()
      print(o)

写文件:

# 写文件
>>> with open('new_file.txt',mode='w',encoding='utf-8') as f:
      w = f.write('I love python\n It\'s so simple')
      os.listdir()

 
['drinksbycountry.csv', 'IMDB-Movie-Data.csv', 'movietweetings', 'new_file.txt', 'test.csv', 'titanic_eda_data.csv', 'titanic_train_data.csv', 'train.csv']
>>> with open('new_file.txt',mode='r',encoding='utf-8') as f:
      o = f.read()
      print(o)
 
I love python
 It's so simple

61.提取后缀名

>>> import os
>>> os.path.splitext('D:/source/dataset/new_file.txt')
('D:/source/dataset/new_file', '.txt') #[1]:后缀名

62.提取完整文件名

>>> import os
>>> os.path.split('D:/source/dataset/new_file.txt')
('D:/source/dataset', 'new_file.txt')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值