1小时搞定Python基础

Python基础

1. 字符串

(拆分:split();插入:join();代替:replace();修剪:strip;格式化输出:’{2} {1} {0}’.format(‘tang’,‘yu’,‘di’))

1.1 切分

ch='a,o,e,i,u,v,b,p,m,f,d,t,n,l,g,k,h,j,q,x,z,c,s,zh,ch,sh,an,en,in,un,yun,ang,eng,ing,ong,'
ch
'a,o,e,i,u,v,b,p,m,f,d,t,n,l,g,k,h,j,q,x,z,c,s,zh,ch,sh,an,en,in,un,yun,ang,eng,ing,ong,'
char=ch.split(',')
char
['a',
 'o',
 'e',
 'i',
 'u',
 'v',
 'b',
 'p',
 'm',
 'f',
 'd',
 't',
 'n',
 'l',
 'g',
 'k',
 'h',
 'j',
 'q',
 'x',
 'z',
 'c',
 's',
 'zh',
 'ch',
 'sh',
 'an',
 'en',
 'in',
 'un',
 'yun',
 'ang',
 'eng',
 'ing',
 'ong',
 '']

1.2 连接

st='!'
tr=st.join(char)
tr
'a!o!e!i!u!v!b!p!m!f!d!t!n!l!g!k!h!j!q!x!z!c!s!zh!ch!sh!an!en!in!un!yun!ang!eng!ing!ong!'

1.3 替换

ch.replace('a','z')
'z,o,e,i,u,v,b,p,m,f,d,t,n,l,g,k,h,j,q,x,z,c,s,zh,ch,sh,zn,en,in,un,yun,zng,eng,ing,ong,'

1.4 修剪

a='   abcdefg    '
a.strip()
'abcdefg'
a='   abcdefg    '
a.lstrip()
'abcdefg    '
a='   abcdefg    '
a.rstrip()
'   abcdefg'
a='abcdefg    '
a.strip('ab')
'cdefg    '

1.5 格式化输出

'{},{},{}'.format('a','b','c')
'a,b,c'
'{2},{1},{0}'.format('a','b','c')
'c,b,a'
'{a},{b},{c}'.format(a=6,b=6,c=6)
'6,6,6'
a = 'a,b,c:'
b = 456.0
c = 789 
result = '%s %f %d' % (a,b,c)
result
'a,b,c: 456.000000 789'

2. 索引与切片

(字符串下标访问) 从前面是0开始 从后面是-1开始;切片(取子串) :表示从哪到哪 左闭右开的区间;A[::-5]每隔5个取一个数,-代表从后面开始取

A="0123456sss"
A[2:8]
'23456s'
A
'0123456sss'
A[-3:]
'sss'
A[-4]
'6'
A[::-5]
's4'

3. 列表[],字典{},集合set()

list: 可以存放任何类型数据;
加,乘操作,切片索引;
增:append(),insert();删:remove(),pop(),del list[];改;查:是否在列表中元素 in list,在列表中的个数:count(元素),查看某元素的索 引:index(元素),排序:sort();
字典: key-value 结构: a[‘first’] = 123; 增:直接添加新的键值对aa[‘nba’]=30,删除:a.pop(‘key’),查:get(key);
集合:set(),保留唯一的元素;运算:交:intersect &,并:union | ,异或:difference - ;增:add(),删:remove()pop(),改:update()

a=[1,'a',0.11,True,{'key1':1,'key2':2}]
a.append("NBA CBA")
a
[1, 'a', 0.11, True, {'key1': 1, 'key2': 2}, 'NBA CBA']
a.insert(0,'W')
a
a.pop()
a
a.remove(0.11)
a
['W', 'W', 'W', 'a', True]
b=[255,255,255]
c=a+b*3
type(c)
list
b.count(255)
3
a.index('a')
3
c
[1,
 2,
 3,
 'a',
 'b',
 'c',
 0.11,
 0.22,
 0.33,
 True,
 False,
 {'key1': 1, 'key2': 2},
 255,
 255,
 255,
 255,
 255,
 255,
 255,
 255,
 255]
del c[-5:]
c
[1,
 2,
 3,
 'a',
 'b',
 'c',
 0.11,
 0.22,
 0.33,
 True,
 False,
 {'key1': 1, 'key2': 2},
 255,
 255,
 255,
 255]
('a'in c)&(0.34 in c)
False
c[2]=9999
c
[1,
 2,
 9999,
 'a',
 'b',
 'c',
 0.11,
 0.22,
 0.33,
 True,
 False,
 {'key1': 1, 'key2': 2},
 255,
 255,
 255,
 255]
d=[9,7,3,6,0,12,54,8,3,2]
d.sort()
d.reverse()
d.reverse()
d
[0, 2, 3, 3, 6, 7, 8, 9, 12, 54]
aa={'nba':30,'cba':20}
aa
{'nba': 30, 'cba': 20}
type(aa)
dict
aa.values()
dict_values([30, 20])
aa.keys()
dict_keys(['nba', 'cba'])
aa.items()
dict_items([('nba', 30), ('cba', 20)])
aa.pop('nba')
30
aa
{'cba': 20}
aa['nba']=30
aa
{'cba': 20, 'nba': 30}
aa.get('cba')
20
aa['nba']=20
aa
{'cba': 20, 'nba': 20}
a=[1,1,2,2,3,3,4,4,5,5,6,6]
a
[1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]
b=set(a)
b
{1, 2, 3, 4, 5, 6}
c={1,2,3}
d={3,4,5}
c.union(d)
{1, 2, 3, 4, 5}
c|d
{1, 2, 3, 4, 5}
c&d
{3}
c.intersection(d)
{3}
c.difference(d)
{1, 2}
d.difference(c)
{4, 5}
c-d
{1, 2}
d-c
{4, 5}

4. 判断,循环,函数,包

创建脚本文件:%%writefile 文件名;%run 文件名;导出:import 文件名(只运行一次)/import 文件名 as 别名;删除:import os,os.remove(文件名);

aaa=123
if aaa<100:
    print('100')
elif aaa==100:
    print('False')
else:
    print(aaa)
123
aaaa=['a','b','c']
while aaaa:
    aaaa.pop()
    print(aaaa)
['a', 'b']
['a']
[]
aaaa=['a','b','c']
for name in aaaa:
    print(name)
a
b
c
bbbb = [123,435,1234]
for i in range(len(bbbb)):
    print (bbbb[i])
123
435
1234
def addd(a,*args):
    b=c=0
    for i in args:
        a+=i
        b+=a
        c+=b
    return a,b,c
a,b,c=addd(1,2,3,4)
print(a,b,c)
10 19 31
def subb(a,**kwargs):
    for arg,value in kwargs.items():
        print(arg,a-value)
subb(1010,x=10,y=20)
x 1000
y 990
%%writefile liu.py
a=100
def addd(b=255,c=0):
    return (b+c)
b=addd(255);
print(b);
Writing liu.py
%run liu.py
255
import liu as l
print(l.a)
print(l.addd(234,432))
100
666
from liu import *
a
100
addd(9999,23987)
33986
import os
os.path.abspath('.')
'C:\\·····`···`······`···················`··`··`·····`············'
os.remove('liu.py')

5. 异常和类

异常处理结构:try{…}except …
类构造函数 def init(self,…):

class MyError(ValueError):
    pass

cur_list = ['a','b','c']
while True:
    cur_input = input()
    if cur_input not in cur_list:
        raise MyError('Invalid input: %s' %cur_input)
a
b
c
aa



---------------------------------------------------------------------------

MyError                                   Traceback (most recent call last)

 in 
      6     cur_input = input()
      7     if cur_input not in cur_list:
----> 8         raise MyError('Invalid input: %s' %cur_input)


MyError: Invalid input: aa
import math

for i in range(10):
    try:
        input_number = input('write a number')
        
        if input_number == 'q':
            break
        result = 1/math.log(float(input_number))
        print (result)
    except ValueError:
        print ('ValueError: input must > 0')
    except ZeroDivisionError:
        print ('log(value) must != 0')
    except Exception:
        print ('ubknow error')
write a number0
ValueError: input must > 0
write a number-0
ValueError: input must > 0
write a number0.00000000000000000000000000000000000000000001
-0.009870329134164814
write a number1
log(value) must != 0
write a numberq
class fruit:
    def __init__(self,name,color,price=0):
        self.name=name
        self.color=color
        self.price=price
    def fruitinformation(self):
        print('The name of fruit is %s, it is %s, its price are %f\n'%(self.name,self.color,self.price))
    def whereproduce(self):
        print('it is from China')

class apple(fruit):
    def __init__(self,name,color,price):
        self.name=name
        self.color=color
        self.price=price
    def whereproduce(self):
        print('it is from Yantai')
f = fruit('banana','yellow',2.5)
f.fruitinformation()
f.whereproduce()
The name of fruit is banana, it is yellow, its price are 2.500000

it is from China
a=apple('apple','red',3.5)
a.fruitinformation()
a.whereproduce()
The name of fruit is apple, it is red, its price are 3.500000

it is from Yantai
hasattr(f,'name')
True
hasattr(a,'whereproduce')
True
getattr(a,'price')
3.5
setattr(a,'price',2.0)
getattr(a,'price')
2.0
delattr(a,'price')
getattr(a,'price')
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

 in 
      1 delattr(a,'price')
----> 2 getattr(a,'price')


AttributeError: 'apple' object has no attribute 'price'

文件操作和时间

文件:
创建:%%writefile 文件名;读:open(路劲文件名,‘r’)/read()/readlines /close();写:open(路劲文件名,‘w’/‘a’)/write()/close()
时间:
导入:import time;time.localtime(time.time());time.asctime(time.localtime(time.time()));

%%writefile lxj.txt
123
456
789
666
'nihao'
Overwriting lxj.txt
f=open('./lxj.txt','r')
txt=f.read()
print(txt)
123
456
789
666
'nihao'
f=open('./lxj.txt','r')
lines=f.readlines()
for line in lines:
    print(line)
123

456

789

666

'nihao'
f.close()
ff=open('./lxj.txt','a')
ff.write('hello\n')
ff.write('world')
ff.close()
f=open('./lxj.txt','r')
txt=f.read()
print(txt)
123
456
789
666
'nihao'
hello
world
f.close()
import time
print (time.localtime(time.time()))
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=23, tm_hour=13, tm_min=46, tm_sec=33, tm_wday=4, tm_yday=235, tm_isdst=0)
print (time.asctime(time.localtime(time.time())))
Fri Aug 23 13:45:34 2019
print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
2019-08-23 13:46:40
import calendar
print (calendar.month(2017,11))
print (help(calendar.month))
   November 2017
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

Help on method formatmonth in module calendar:

formatmonth(theyear, themonth, w=0, l=0) method of calendar.TextCalendar instance
    Return a month's calendar string (multi-line).

None

你可能感兴趣的:(人工智能)