數據館員的 Python 簡明手冊
1. hello world
__author__ = 'zuoy'
__doc__ = '在屏幕上打印信息: hello world!'
def main():
'''
入參:無
功能:在屏幕上打印信息: hello world!
'''
print('hello world!')
if __name__ == '__main__':
main()
2. 數據類型
string
s.split(str, num)
s.upper()
s.lower()
list
for num in l:
len(l)
- 刪除list、list元素(與字典刪除操作同方法)
l.pop(index)
del l[index]
del l
l.append(x)
l.insert(index)
l.index(x)
nl = l[start_index : end_index+1 : step]
nl = [m + n for m in 'ABC' for n in 'XYZ']
l.sort(k=f)
nl = sorted(l, key=abs, reverse=True)
l3 = zip(l1, l2)
for x, y in l3:
map(f, l
reduce(f, []1,2,3)
filter(is_odd, l)
字典
for k in d:
for v in d.values()
for k, v in d.items()
- 刪除dict、dict元素(與list刪除操作同方法)
d.remove(k)
del d[k]
del d
if k in d:
if d.get(k, None) != None:
set
字典的key集合,不重
d.add(k)
d.remove(k)
d1 + d2
d1 | d2
枚舉類型
from enum import Enum
Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
print(Month.Feb) == Month.Feb
from enum import Enum, unique
@unique
class Weekday(Enum):
Sun = 0
Mon = 1
Tue = 2
Weekday.Mon == Weekday.Mon
Weekday.Tue.value == 2
邏輯運算符
x and y
x or y
not x
常用方法
isinstance(x, int)
type(x) == int
range(s, e, step)
with open(file, encoding='utf-8', 'r') as f:
f.read()
f.readlines()
f.readline()
f.read(n)
os.path.abspath('.')
os.path.join('/Users', 'testdir')
os.mkdir('/Users')
os.rmdir('/Users')
os.path.splitext('/path/to/file.txt')
os.path.split('/Users/michael/testdir/file.txt')
os.rename('test.txt', 'test.py')
os.remove('test.py')
os.listdir('.')
os.path.isdir(x)
os.path.isfile(x)
注意
除法
10 / 3 == 3
//
10 // 3 == 3
-10 / 3 == -4
參考
linux安裝python