硬货满满,30个Python源代码

1.十进制转换为二进制

>>> bin(10)
'0b1010'

2.十进制转换为八进制

>>> oct(9)
'0o11'

3.十进制转换为十六进制

>>> hex(15)
'0xf'

4.字符串转换为字节类型

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

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

>>> i = 100
>>> str(i)
'100'

6.十进制整数对应的 ASCII 字符

>>> chr(65)
'A'

7.ASCII字符对应的十进制数

>>> ord('A')
65

8.整数或数值型字符串转换为浮点数

>>> float(3)
3.0

9.创建数据字典的几种方法

>>> 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}

10.排序函数

>>> 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'}]

11.求和函数

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

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

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

13.获取用户输入内容

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

14.print 用法

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

15.格式化字符串常见用法

>>> 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

值(值得注意,自定义的实例都可哈希,listdictset等可变对象都不可哈希)

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

16.if not x

直接使用 x 和 not x 判断 x 是否为 None 或空

x = [1,3,5]

if x:
    print('x is not empty ')

if not x:
    print('x is empty')

17.打开文件,并返回文件对象

>>> 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,"

18. 创建迭代器

>>> 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

19.创建range迭代器

>>> t = range(11)
>>> t = range(0,11,2)
>>> for e in t:
     print(e)

0
2
4
6
8
10

20.反向

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

21.打包

>>> 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

22.过滤器

函数通过 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

23. split 分割**

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

24. 提取后缀名

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

25.斐波那契数列前n项

>>> def fibonacci(n):
      a, b = 1, 1
      for _ in range(n):
        yield a
        a, b = b, a+b # 注意这种赋值

>>> for fib in fibonacci(10):
      print(fib)

 
1
1
2
3
5
8
13
21
34
55

26.list 等分 n 组

>>> from math import ceil
>>> def divide_iter(lst, n):
      if n <= 0:
        yield lst
        return
      i, div = 0, ceil(len(lst) / n)
      while i < n:
        yield lst[i * div: (i + 1) * div]
        i += 1

  
>>> for group in divide_iter([1,2,3,4,5],2):
      print(group)

 
[1, 2, 3]
[4, 5]

27. 列表生成式

data = [1, 2, 3, 5, 8]
result = [i * 2 for i in data if i & 1] # 奇数则乘以2
print(result) # [2, 6, 10]

28.字典生成式

keys = ['a', 'b', 'c']
values = [1, 3, 5]

d = {k: v for k, v in zip(keys, values)}
print(d)

29.判断字符串是否包含某个子串,使用in明显更加可读

x = 'zen_of_python'
if 'zen' in x:
    print('zen is in')

30.zip 打包

使用 zip 打包后结合 for 使用输出一对

keys = ['a', 'b', 'c']
values = [1, 3, 5]

for k, v in zip(keys, values):
    print(k, v)

硬货满满,30个Python源代码_第1张图片 

 

你可能感兴趣的:(python)