python相关知识点

python笔记:

1.print

print(1)/ print(1+1)
print("你")
print('I\' m m ')
print('apple'+'4')
print('apple'+str(4))
print(float('1.2')+2)
appele = 10
print(apple)  #此时的输出为10
print(a[0:3]) #输出a[0]-a[3]的值
s = """hello
world"""
print (s)  #三引号用来输入包含多行文字的字符串
a = [10, 11, 12, 13, 11]
print(10 in a)
print(10 not in a) #判断列表中是否存在对应元素

数字/数字计算式直接表达 。

字符串等用" "或‘ ’表达。

当只使用单引号时,注意用\区分出字符跟命令。

两个字符串相加时,等于将后面一个字符串内容加到前一个字符串后(str功能与’'相同)。

对字符串的相关操作:

(1).字符串的分割:
s = "hello world"
s.split() #以(包括多个空格,制表符\t,换行符\n等)为标识,分割字符串
#输出  ['hello', 'world']
line = "1 2 3 4 5"
numbers = line.split()
print (numbers)
#['1', '2', '3', '4', '5']

​ 可对字符串进行多次分割。

(2).与加减乘除的使用
s = 'hello ' + 'world'   #加法  输出'hello world'
"echo" * 3 	#乘法  输出'echoechoecho'
len(s)   #输出字符串长度
(3).字符串的连接

​ 与分割相反,s.join(str_sequence)的作用是以s为连接符将字符串序列str_sequence中的元素连接起来,并返回连接后得到的新字符串

s = ' '
s.join(numbers)
#输出'1 2 3 4 5'
s = ','
s.join(numbers)
#输出'1,2,3,4,5'

基于上述numbers = [‘1’, ‘2’, ‘3’, ‘4’, ‘5’]的基础上

(4).字符串的替换

​ s.replace(part1, part2)将字符串s中指定的部分part1替换成想要的部分part2,并返回新的字符串。

s = "hello world"
s.replace('world', 'python')
#'hello python'

​ 此时,s的值并没有变化,替换方法只是生成了一个新的字符串。即s还是’hello world’.

(5).字符串的大小写转换

​ s.upper()方法返回一个将s中的字母全部大写的新字符串。

​ s.lower()方法返回一个将s中的字母全部小写的新字符串。

"hello world".upper()
#'HELLO WORLD'
s = "HELLO WORLD"
print (s.lower())
print (s)
#hello world	HELLO WORLD
(6).去除多余空格

​ s.strip()返回一个将s两端的多余空格除去的新字符串。

​ s.lstrip()返回一个将s开头的多余空格除去的新字符串。

​ s.rstrip()返回一个将s结尾的多余空格除去的新字符串。

​ s的值依旧不会变化

s = ' hello world '
s.strip()
#'hello world'
#s还是 ' hello world '

注意:dir函数可查看所有可以使用的方法。

(7).用()或\来换行

当代码太长了以后,我们可以使用()或’ \ '来将一行代码转换为多行代码。

a = ('hello world.'
    "it's a nice day. "
    "my name is xxx")
a = 'hello world.'\
    "it's a nice day."\
    "my name is xxx"
#"hello, world. it's a nice day. my name is xxx"
(8).强制转换为字符串

​ str()与repr()都可以将强制转换为字符串类型。

str(1.1+2.2)
repr(1.1+2.2)
#'3.3000000000000003'
(9).整数与不同进制的字符串转换
#十六进制
hex(255)
#'0xff'

#八进制
oct(255)
#'0o377'

#二进制
bin(255)
#'0b11111111'

int('FF', 16)
#255   后面的16为进制的选择
(10).格式化字符串

​ Python用字符串的format()方法来格式化字符串。

​ 具体用法如下,字符串中花括号 {} 的部分会被format传入的参数替代,传入的值可以是字符串,也可以是数字或者别的对象。

'{} {} {}'.format('a', 'b', 'c')
#'a b c'
'{1} {2} {0}'.format('a', 'b', 'c')
#可以用数字指定传入参数的相对位置   'b c a'
'{color} {0} {x} {1}'.format(10, 'foo', x = 1.5, color='blue')
#'blue 10 1.5 foo'
from math import pi
'{0:5}{1:2d}{2:10.2f}'.format('foo',5,2*pi)
#'foo    5       6.28'
(11).分片
var[lower:upper:step]
myStr = 'abcdefg' 
myStr[::-1]
#'gfedcba'

2.数学计算

注意(±*/%还是跟C语言一般,直接使用就好)

2**4  #表示2的4次方
10//3 #结果为3

整数除法,返回的是比结果小的最大整数值:

12.3 // 5.2   #输出2.0
12.3 // -4    #输出-4.0
#	取整:
round(21.6)  #22
#	最大、小值
print (min(2, 3, 4, 5)) #2
print (max(2, 4, 3)) # 4

布尔型:

q = True
type(q)  #bool

q = 1 > 2
print (q) #False

3.while / for / if

(1).作用域( 表达式后面要加:)

while condition<10:
    print(condition)
    condition=condition+1

( if / for的作用域与其相同 )

(2).运算条件

while ture/false

( if / for的条件与其相同 ture or false(或者正确或错误的语句) )

(3).可运用列表

定义列表:
example_list = [1,2,3,4,5,6]  ##数字不用加'',字符需要''
运用:
for i in example_list:
    print(i)
print("over")
特殊:
for i in range(1,10,1):   ##只会输出1-9而不会输出10,第三个1为步长
    print(i)

(4). if

可用表达式 : xm

表示相等时:x==y (单个=表示赋值)

多情况:

if x<1:
    print(1)
elif x>1:
    print(2)
else:
    print(3)

4.函数

简单例子:

def fuction():
    a=1
    a++
    print(a)

含参数(需要给定a b):

def fuction(a,b):
    a=1
    b++
    print(a b)

默认函数参数:

def sale_car(price,color,brand,is_second_hand):
    print('price:',price
         'color:',color
         'brand:',brand
         'is_second_hands',is_second_hand)
sale_car(1000,'red','carmmy',Ture)  ##若函数定义时就已经给初值则此时调用要sale_car(price = 2000)改变初值
def add(x, *args):
    total = x
    for arg in args:
        total += arg
    return total
#这里,*args 表示参数数目不定,可以看成一个元组,把第一个参数后面的参数当作元组中的元素。
def add(x, **kwargs):
    total = x
    for arg, value in kwargs.items():
        print("adding %s=%s"%(arg,value))
        total += value
    return total
#这里, **kwargs 表示参数数目不定,相当于一个字典,键和值对应于键值对。

5.文件的读写

text = 'This is my first test.\n This is the next line.'
my_file = open('my file.txt','w')  ## 'my file.test'表示打开的文件  'w'表示文件打开方式为读写
my_file.write(text)
my_file.close  ##文件用完要关闭  十分重要
append_text = '\n This is appended file.'
my_file = open('my file.text','a')
my_file.write(append_text)
my_file.close
file = open('my file.text','r')
content = file.read()
## file.readline()表示输出文件中的一行,第一次出现输出第一行,第二次出现输出第二行
## file.readlines()表示输出全部内容
print(content)

6.Class类

class Calculator:
    name = 'ye'
    #def__init__(self,name,price)      init给予初值————类似默认函数参数
    #self.name=name  self.price=price   
    def add(self,x,y):
        print(x+y)
    def minus(self,x,y):
        print(x-y)
    def times(self,x,y):
        print(x*y)
    def divide(self,x,y):
        print(x/y)
cal = Calculator()   ##定义个体
cal.name             ##表示属性
cal.add(10,11)       ##运用计算属性

7.input

a_input = int(input('please give a number:')	#给a_input赋值
if a_input == 1:
    print('This is a good one')
elif a_input == 2:
    print('See you next time')
else :
    print('Bye')

8.元组

(tuple)

​ 元组是有序的,因此 ('New York', 'Austin')('Austin', 'New York') 是两个不同的键

a_list  = [12,3,4,5,6]
for index in range(len(a_list)):
    print('index = ',index,  #输出0-4
          'number in list = ',a_list[index]) #输出列表中对应的数

​ 元组不可变。

9.列表

常见操作:

#加法
a = [1, 2, 3]
b = [3.2, 'hello']
a + b
#[1, 2, 3, 3.2, 'hello']

#乘法
a * 3
#[1, 2, 3, 1, 2, 3, 1, 2, 3]

一维:

a = [1,2,3,4,5]
a.append(0) #在列表最后加0
a.extend(['a','b']) #在列表里最后加'a,b'
a.insert(1,0) #前者表示加入位置,后者表示加入的值
a.pop() #l.pop(idx) 会将索引 idx 处的元素删除,并返回这个元素。未指定 idx 时,默认为列表最后一个元素。
a.remove(2) #删除第一个出现的2
a.index(2) #记录第一次出现2的位置
a.count(2)#计算2出现的次数
a.sort()#从小到大排序
a.sort(reverse = Ture) #从大到小排序
#如果不想改变原来列表中的值,可以使用 sorted 函数
b = sorted(a)

多维:

a = [[1,2,3],
     [2,3,4],
     [3,4,5]]
print(a[2][2])  #输出5

10.dictionary字典

​ 用{}或者dict()创建一个空的字典。

d  = {'apple':1,'pear':2,'orange':3}
print(d['apple']) #	输出值为1
del d['pear']  #删除pear
d['b'] = 20 #在字典任意位置添加上d['b']
d = {'apple':[1,2,3],'pear':{1:3,3:'a'},'orange':2}
print(d['pear'][3])  #输出a

11.错误处理

tryfile = open('eeee','r')
except Exception as e:  #如果出错则把错误存在e里
    print(e)
    response = input('do you want to creat a new file')
    if  response == 'y':
    	file = open('eeee','w')
    else:
        pass 
else:   #未出错,写入ssss
    file.write('ssss')
file.close()

12.zip lambda map

a = [1,2,3]
b = [4,5,6]
zip(a,b)  #将a、b对应位的数据合起来,形成[(1,4)(2,5)(3,6)]
zip(a,a,b)  #也可实现对应功能
fun1 = lambda x,y:x+y  #类似函数功能,引用为fun1(2,3)
map(fun1,[1],[2])   #输出还是fun1的结果,但是要输出为list类型

13.深复制、浅复制

import copy
a = [1,2,3]
b = a   #a、b索引相同,改变a也改变b
c = copy.copy(a) #浅复制,改变c不会改变a,但是如果a中数据为list类型则也会改变
d = copy.deepcopy(a)#完全复制,改变a不改变d

14.集合

​ 可以用set()函数来显示的生成空集合

a = set([1, 2, 3, 1])
#{1, 2, 3}	集合会自动去除重复元素 1。

​ 但是创建空集合的时候只能用set来创建,因为在Python中{}创建的是一个空的字典

并:

​ 两个集合的并,返回包含两个集合所有元素的集合(去除重复)。

​ 可以用方法 a.union(b) 或者操作 a | b 实现。

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a.union(b)
b.union(a)
#{1, 2, 3, 4, 5, 6}

交:

​ 两个集合的交,返回包含两个集合共有元素的集合。

​ 可以用方法 a.intersection(b) 或者操作 a & b 实现。

a.intersection(b)
a & b
#{3, 4}

差:

ab 的差集,返回只在 a 不在 b 的元素组成的集合。

可以用方法 a.difference(b) 或者操作 a - b 实现。

a.difference(b)
a - b
#{1, 2}

对称差:

​ a 和b 的对称差集,返回在 a 或在 b 中,但是不同时在 a 和 b 中的元素组成的集合。

​ 可以用方法 a.symmetric_difference(b)或者操作 a ^ b`实现(异或操作符)。

a.symmetric_difference(b)
a ^ b
#{1, 2, 5, 6}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值