赞
踩
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
30个Python源代码
>>> bin(10)
'0b1010'
>>> oct(9)
'0o11'
>>> hex(15)
'0xf'
>>> s = "apple"
>>> bytes(s,encoding='utf-8')
b'apple'
>>> i = 100
>>> str(i)
'100'
>>> chr(65)
'A'
>>> ord('A')
65
>>> float(3)
3.0
>>> 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}
>>> 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'}]
>>> a = [1,4,2,3,1]
>>> sum(a)
11
#求和初始值为1
>>> sum(a,1)
12
>>> s = "1 + 3 +5"
>>> eval(s)
9
>>> eval('[1,3,5]*3')
[1, 3, 5, 1, 3, 5, 1, 3, 5]
>>> input()
I'm typing
"I'm typing "
>>> lst = [1,3,5]
#f 打印
>>> print(f'lst: {lst}')
lst: [1, 3, 5]
#format 打印
>>> print('lst:{}'.format(lst))
lst:[1, 3, 5]
>>> 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 值(值得注意,自定义的实例都可哈希,list, dict, set等可变对象都不可哈希) >>> class Student(): def __init__(self,id,name): self.id = id self.name = name >>> xiaoming = Student('001','xiaoming') >>> hash(xiaoming) -9223371894234104688
直接使用 x 和 not x 判断 x 是否为 None 或空
x = [1,3,5]
if x:
print('x is not empty ')
if not x:
print('x is empty')
>>> 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,"
>>> 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
>>> t = range(11)
>>> t = range(0,11,2)
>>> for e in t:
print(e)
0
2
4
6
8
10
>>> rev = reversed([1,4,2,3,1])
>>> for i in rev:
print(i)
1
3
2
4
1
>>> 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
函数通过 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
>>> 'i love python'.split(' ')
['i', 'love', 'python']
>>> import os
>>> os.path.splitext('D:/source/dataset/new_file.txt')
('D:/source/dataset/new_file', '.txt') #[1]:后缀名
>>> 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
>>> 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]
data = [1, 2, 3, 5, 8]
result = [i * 2 for i in data if i & 1] # 奇数则乘以2
print(result) # [2, 6, 10]
keys = ['a', 'b', 'c']
values = [1, 3, 5]
d = {k: v for k, v in zip(keys, values)}
print(d)
x = 'zen_of_python'
if 'zen' in x:
print('zen is in')
使用 zip 打包后结合 for 使用输出一对
keys = ['a', 'b', 'c']
values = [1, 3, 5]
for k, v in zip(keys, values):
print(k, v)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。