python学习手册中的一些易忘的点(前三部分)
1.ubuntu下让python脚本可直接运行:
test.py文件(后缀可省)
#!/usr/bin/python
print('wwwww')
sudo chmod +x ./test.py (sudo chmod 755 ./2)
执行./test.py即可
可添加为快捷方式:
sudo ln -s /home/zh/桌面/test.py /usr/bin/test
执行test
2.取出0-20中,能够被3整除的数(列表解析)
>>> [x for x in range(0,20) if x % 3 ==0]
[0, 3, 6, 9, 12, 15, 18]
>>>
3.运行一个脚本
>>> a="{1:1,2:2,'1':22}"
>>> eval(a)
{'1': 22, 1: 1, 2: 2}
>>> b=eval(a)
>>> type(b)
<type 'dict'>
>>> eval('list("qqqqqqqqqqq")')
['q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q', 'q']
4.字符与数字转换
>>> chr(115)
's'
>>> ord('c')
99
5.字符串格式化
>>> 'aaaa %s bbbbb %s ccccc' % (1,2)
'aaaa 1 bbbbb 2 ccccc'
>>>
>>> t='{}+{}={}'.format(1,2,3)
>>> t
'1+2=3'
>>>
6.字典与列表解析
>>> dict([(1,1),(2,2)])
{1: 1, 2: 2}
>>> zip([1,2,3],[1,2,3])
[(1, 1), (2, 2), (3, 3)]
>>> {a:b*2 for (a,b) in [(1, 1), (2, 2), (3, 3)]}
{1: 2, 2: 4, 3: 6}
>>>
7.对象序列化/保存到文件
>>> dic = {'age': 23, 'job': 'student','11':[1,2,3,4]}
>>> byte_data = pickle.dumps(dic)
>>> byte_data
"(dp0\nS'11'\np1\n(lp2\nI1\naI2\naI3\naI4\nasS'age'\np3\nI23\nsS'job'\np4\nS'student'\np5\ns."
>>> obj = pickle.loads(byte_data)
>>> obj
{'11': [1, 2, 3, 4], 'age': 23, 'job': 'student'}
>>>
#到文件
>>> with open('abc.pkl', 'wb') as f:
... dic = {'age': 23, 'job': 'student'}
... pickle.dump(dic, f)
...
>>> with open('abc.pkl', 'rb') as f:
... aa = pickle.load(f)
... print(aa)
... print(type(aa)) # <class 'dict'>
...
{'age': 23, 'job': 'student'}
<type 'dict'>
用户自定义对象
序列化用户自定义对象
假如我写了个类叫做Person
class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job
def work(self):
print(self.name, 'is working...')
pickle当然也能写入,不仅可以写入类本身,也能写入它的一个实例。
# 将实例存储在变量中,当然也能存在文件中
a_person = Person('abc', 22, 'waiter')
person_abc = pickle.dumps(a_person)
p = pickle.loads(person_abc)
p.work()
# 将类本身存储在变量中,loads的时候返回类本身,而非它的一个实例
class_Person = pickle.dumps(Person)
Person = pickle.loads(class_Person)
p = Person('Bob', 23, 'Student')
p.work()
# 下面这个例子演示的就是将类存储在文件中
# 序列化
with open('person.pkl', 'wb') as f:
pickle.dump(Person, f)
# 反序列化
with open('person.pkl', 'rb') as f:
Person = pickle.load(f)
aa = Person('gg', 23, '6')
aa.work()
更多json,shelve序列化参考这里[Python序列化和反序列化]
8.实现类似python3的打印
>>> from __future__ import print_function
>>> for line in open('/home/zh/桌面/笔记'):print(line,'')
打印重定向
import sys
f=open('test.txt','a+')
a='123'
b='456'
print >> f,a,b
f.close()
--------------
import sys
f=open('a.txt','w')
old=sys.stdout #将当前系统输出储存到临时变量
sys.stdout=f #输出重定向到文件
print 'Hello World!' #测试一个打印输出
sys.stdout=old #还原系统输出
f.close()
print open('a.txt','r') # 错误的方法,仅用于查看输出,了解python
print open('a.txt','r').read()
更多参考
9.赋值语句中进行条件判断
>>> c='1111122222333334444455555'
>>> d=c[:5]+'#'+c[5:] if len(c)<5 else (c[:5]+'#'+c[5:10]+'#'+c[10:] if len(c)==15 else (c[:5]+'#'+c[5:10]+'#'+c[10:15]+'#'+c[15:] if len(c)==20 else (c[:5]+'#'+c[5:10]+'#'+c[10:15]+'#'+c[15:20]+'#'+c[20:] if len(c)==25 else 3)))
>>> d
'11111#22222#33333#44444#55555'
>>>
10.zip与map,enumerate
>>> a
[1, 2, 3]
>>> b
[5, 6, 7]
>>> zip(a,b)
[(1, 5), (2, 6), (3, 7)]
>>> type(zip(a,b))
<type 'list'>
>>> map(chr,a)
['\x01', '\x02', '\x03']
>>> p=['1','2','3']
>>> enumerate(p)
<enumerate object at 0x7f93e36688c0>
>>> type(enumerate(p))
<type 'enumerate'>
>>> for ii in enumerate(p):print(ii)
...
(0, '1')
(1, '2')
(2, '3')
>>> n=enumerate(p)
>>> next(n)
(0, '1')
>>>
11.获取帮助
dir(sys)
help(sys)