python基础语法二

书接上回:

python基础语法一

4. 列表

4.1 列表的特点

(1)列表元素有序,有索引去获取特定的元素,从前往后索引从0递增,从后往前索引从-1递减

(2)列表可存放相同value的元素

(3)列表元素类型可以不同

(4)可以使用+进行拼接,*表示重复

4.2 列表的创建

(1)方式一:使用方括号[];空列表=[]

(2)方式二:使用内置函数list();空列表=list()

(3)方式三:创建固定大小的空列表:空列表=[None]*个数

4.2

lst1 = ['ad', 10]

lst2 = list(['ad', 10, True, 'aaa', 56])

print(lst2[-2]) #aaa

4.3 列表的查询

(1)元素  in   列表

(2)元素  not in  列表

4.3

lst2 = list(['ad', 10, True, 'aaa', 56])

print('ad' in lst2) #True

print('ad' not in lst2) #False

4.4 列表的获取

(1)获取特定元素的索引:index(),注意:若存在多个相同的元素,只返回第一个元素的索引;若元素不存在,会抛出异常;在指定范围内查找: index(元素,start, stop) [start:stop)左闭右开的集合

(2)获取指定单个索引的元素:list[x]:索引x:从前往后索引从0递增,从后往前索引从-1递减。若索引超出范围会抛出异常

(3)获取多个元素:切片操作:列表名[start:stop:step],[start, stop)左闭右开,切出来的列表是一个新的对象,start默认为0, stop默认最后一个, step默认1, step为负数会反序

4.4

lst2 = list(['ad', 10, True, 'aaa', 56])

print(lst2.index(10)) #1

print(lst2.index(10, 0, 2)) #1

print(lst2[0:1:1]) #['ad']

print(lst2[0:3]) #['ad', 10, True]

print(lst2[0:3:]) #['ad', 10, True]

print(lst2[:3:1]) #['ad', 10, True]

print(lst2[1::1]) #[10, True, 'aaa', 56]

print(lst2[1::]) #[10, True, 'aaa', 56]

print(lst2[::])#['ad', 10, True, 'aaa', 56]

print(lst2[::-1]) #[56, 'aaa', True, 10, 'ad']

print(lst2[-1:-3:-1]) #[56, 'aaa']

4.5 列表的增加

(1)列表.append(元素):在列表最后添加,没有创建新的列表对象

(2)列表1.append(列表2):将列表2当作一个元素添加到列表1里,会产生列表的嵌套

(3)列表1.extend(列表2):在列表1后面添加列表2

(4)列表.insert(位置,元素):在任意位置添加元素

(5)列表1[位置1:位置2]=列表2:将列表1的位置1到位置2的元素替换成列表2

4.5

lst1 = [1,2]

lst2 = [3,4]

lst1.append(lst2)  #[1,2,[3,4]]

lst1 = [1,2]

lst2 = [3,4]

lst1.extend(lst2)  #[1,2,3,4]

lst2.insert(1, 'hello')

print(lst2) #[3,’hello’,4]

lst2[len(lst2):] = ['new1', 'new2']

print(lst2) #[3,’hello’,4, 'new1', 'new2']

4.6 列表的删除

(1)列表.remove(元素):从列表中移除该元素,如果该元素有重复,则移除第一个元素,没有该元素则会报错

(2)列表.pop(位置):移除该位置的元素,默认是末尾

(3)列表2=列表1[位置1:位置2]:将列表1的位置1到位置2的元素切片赋值给列表2

(4)列表1[位置1:位置2]=[]:将列表1的位置1到位置2的元素删除

(5)列表.clear():清空该列表

(6)del 列表名:把列表对象整个删除了

(7)del 列表名[index]:删除该位置的元素

4.6

lst2 = list(['ad', 10, True, 'aaa', 56, 'hello', 'woo', 'abc', 99, 'new1', 'new2'])

lst2.remove('aaa')

print(lst2) #['ad', 10, True, 56, 'hello', 'woo', 'abc', 99, 'new1', 'new2']

lst2.pop(1)

print(lst2)# ['ad', True, 56, 'hello', 'woo', 'abc', 99, 'new1', 'new2']

lst2.pop()

print(lst2)# ['ad', True, 56, 'hello', 'woo', 'abc', 99, 'new1']

lst = lst2[1:3]

print(lst)# [True, 56]

lst2[2:4] = []

print(lst2)# ['ad', True, 'woo', 'abc', 99, 'new1']

lst2.clear()

print(lst2)#[]

del lst2

4.7 列表的修改

(1)列表[位置]=元素x:将列表该位置的元素换成元素x

4.7

lst2 = list(['ad', 10, True, 'aaa', 56])

lst2[2:4] = [5,10]

print(lst2)# ['ad', 10, 5, 10, 56]

4.8 列表的排序

(1)列表.sort():默认从小到大排序,没有产生新对象

(2)列表.sort(reverse=True):降序排序

(3)列表2=sorted(列表1,reverse=True/False):使用内置函数,产生新对象

4.8

lst = [1,5,9,0,15,54,32,97]

lst.sort()

print(lst)# [0, 1, 5, 9, 15, 32, 54, 97]

lst.sort(reverse=True)

print(lst)# [97, 54, 32, 15, 9, 5, 1, 0]

lst1 = sorted(lst)

print(lst1)# [0, 1, 5, 9, 15, 32, 54, 97]

lst1 = sorted(lst, reverse=True)

print(lst1)# [97, 54, 32, 15, 9, 5, 1, 0]

4.9 列表的遍历

(1)for  迭代变量  in   列表:

                操作

4.9

lst2 = list(['ad', 10, True, 'aaa', 56])

for i in lst2:

    print(i)

4.10 列表的长度

(1)len(列表)

4.10

lst2 = list(['ad', 10, True, 'aaa', 56])

print(len(lst2)) #5

4.11 列表生成式

(1)[i for i in range(1,10)]

4.11

lst = [i for i in range(1, 10)]

print(lst)# [1, 2, 3, 4, 5, 6, 7, 8, 9]

lst = [i*2 for i in range(1, 10)]

print(lst)# [2, 4, 6, 8, 10, 12, 14, 16, 18]

5. 字典

5.1 字典的特点

(1)字典中的元素是以键值对的形式存在的,以{}包起来

(2)字典是一个无序的序列

(3)key不允许重复,value可以重复

(4)key必须是一个不可变对象:整数值、字符串

(5)字典所占内存很大

5.2 字典的创建

(1)方式一:字典名={'键名':值1,'键名':值2};空字典={}

(2)方式二:字典对象=dict(键名=值1,键名=值2);空字典=dict()

5.2

dict1 = {'A':100, 'B':90, 'C':56}

dict2 = dict(name='A', age=18)

dict3 = {} # 空字典

print(dict1)# {'A': 100, 'B': 90, 'C': 56}

print(dict2)# {'name': 'A', 'age': 18}

print(dict3)# {}

5.3 字典的查询

(1)键是否存在:in/not in

5.3

dict1 = {'A':100, 'B':90, 'C':56}

print('A' in dict1)#True

print('AAA' not in dict1)#True

5.4 字典的获取

(1)获取key:字典名.keys():类型是dict_keys;将key转换成list:list(字典名.keys()):类型:list

(2)获取value:

方式一:字典名.values():类型是dict_values;将value转换成list:list(字典名.values()):类型是list

方式二:字典对象[键名]:键不存在时会抛出KeyError异常

方式三:字典对象.get(键名):键不存在时不会抛出异常,会返回一个none

(3)获取key和value:字典名.items():类型是字典;将key和value转换成元组:list(字典名.items()):类型是元组

5.4

dict1 = {'A':100, 'B':90, 'C':56}

print(dict1['A']) #100

print(dict1.get('AAA')) #error

print(dict1.get('B')) #90

print(dict1.get('AAA')) #输出None

print(dict1.get('BBB',99)) #99是查找不存在时提供的默认值,即若'BBB'键值不存在,会输出99

dict2 = {'name': 'A', 'age': 18, 'home': 'Japan'}

print(dict2.keys())#dict_keys(['name', 'age', 'home'])

print(type(dict2.keys()))#<class 'dict_keys'>

print(list(dict2.keys()))#['name', 'age', 'home']

print(dict2.values())#dict_values(['A', 18, 'Japan'])

print(type(dict2.values()))#<class 'dict_values'>

print(list(dict2.values()))#['A', 18, 'Japan']

print(dict2.items())#dict_items([('name', 'A'), ('age', 18), ('home', 'Japan')])

print(type(dict2.items()))#<class 'dict_items'>

print(list(dict2.items()))#[('name', 'A'), ('age', 18), ('home', 'Japan')]

5.5 字典的增加

(1)字典对象[新键名]=值1

5.5

dict2 = dict(name='A', age=18)

dict2['home'] = 'China'

print(dict2)# {'name': 'A', 'age': 18, 'home': 'China'}

5.6 字典的删除

(1)字典元素的删除:del 字典对象[键名]

(2)清空字典:字典对象.clear()

5.6

dict1 = {'A':100, 'B':90, 'C':56}

del dict1['A']

print(dict1)# {'B': 90, 'C': 56}

dict1.clear()

print(dict1)#{}

5.7 字典的修改

(1)字典对象[旧键名]=新值

5.7

dict2 = {'name': 'A', 'age': 18, 'home': 'China'}

dict2['home'] = 'Japan'

print(dict2)# {'name': 'A', 'age': 18, 'home': 'Japan'}

5.8 字典的遍历

(1)for item in 字典名  #item获取到的是字典的键

5.8

dict2 = {'name': 'A', 'age': 18, 'home': 'Japan'}

for item in dict2:

    print(item)

    print(dict2[item])

5.9 字典生成式

(1)zip():将两个列表生成一个字典

5.9

需求:希望最后生成的字典应该是:{'A': 55, 'B':67, 'C':19}

items = ['a', 'B', 'C']

prices = [55, 67, 19]

dict1 = {item: price for item,price in zip(items, prices)}

print(dict1)# {'a': 55, 'B':67, 'C':19}

dict2 = {item.upper(): price for item,price in zip(items, prices)}

print(dict1)# {'A': 55, 'B':67, 'C':19}

6. 集合

6.1 集合的特点

(1)集合是一种可变类型

(2)集合是没有value的字典

(3)集合中的元素不允许重复

(4)集合中的元素是无序的

6.2 集合的创建

(1)方式一:{}

(2)方式二:使用内置函数set()

6.2

set1 = {55, 'AA', 5.6, 55}

print(set1)# {55, 5.6, 'AA'}

set2 = set(range(6))

print(set2)# {0, 1, 2, 3, 4, 5}

set5 = set() #空集合

print(set5)# set()

6.3 集合的查询

(1)in/not in

6.3

set3 = set((1, 5, 99, 3, 56))

print(1 in set3)#True

print(1 not in set3)#False

6.4 集合的增加

(1)方式一:集合名.add(元素)

(2)方式二:集合名.update(多个元素):可以放集合、列表、元组

6.4

set5 = set()

set5.add(90)

print(set5)# {90}

set5.update({66, 88})  #添加集合

print(set5)# {88, 90, 66}

set5.update([12, 34]) #添加列表

print(set5)# {34, 66, 12, 88, 90}

set5.update((36, 33)) #添加元组

print(set5)# {33, 34, 66, 36, 12, 88, 90}

6.5 集合的删除

(1)方式一:集合名.remove(元素):一次删除一个指定的元素,若元素不存在,抛出异常

(2)方式二:集合名.discard(元素):一次删除一个指定的元素,若元素不存在,不抛出异常

(3)方式三:集合名.pop():没有参数,一次只删除一个任意元素

(4)方式三:集合名.clear():清空集合

6.5

set5 = {33, 34, 66, 36, 12, 88, 90}

set5.remove(34)

print(set5)# {33, 66, 36, 12, 88, 90}

set5.discard(99)

print(set5)# {33, 66, 36, 12, 88, 90}

set5.pop()

print(set5)# {66, 36, 12, 88, 90}

set5.clear()

print(set5)# set()

6.6集合的关系

(1)两个集合是否相等:== /!=

(2)一个集合是否是另一个集合的子集:子集.issubset(父集)

(3)一个集合是否是另一个集合的超集:父集.issuperset(子集)

(4)两个集合是否有交集:集合1.isdisjoint(集合2), 有交集为false

6.6

set1 = {10, 30, 40, 50}

set2 = {30, 10, 40, 50}

print(set1 == set2)#True

print(set1 != set2)#False

set3 = {10}

print(set3.issubset(set1))# True

print(set1.issuperset(set3))# True

print(set3.isdisjoint(set1))  # False

6.7 两个集合的操作

(1)交集操作:s1.intersection(s2)或者s1&s2

(2)并集操作:s1.union(s2)或者s1|s2

(3)差集操作:s1.difference(s2)或者s1-s2

(4)对称差集操作:s1.symmetric_difference(s2)

6.7

set1 = {10, 20, 30}

set2 = {20, 30, 40}

print(set1.intersection(set2))# {20, 30}

print(set1 & set2)# {20, 30}

print(set1.union(set2))# {20, 40, 10, 30}

print(set1 | set2)# {20, 40, 10, 30}

print(set1.difference(set2))# {10}

print(set1 - set2)# {10}

print(set1.symmetric_difference(set2))# {40, 10}

6.8 其他类型转集合

(1)列表转集合:集合1=set(列表)

(2)元组转集合:集合2=set(元组)

(3)字符串转集合:集合3=set(字符串)

6.8

set2 = set([1, 2, 4, 6, 7])

print(set2)# {1, 2, 4, 6, 7}

set3 = set((1, 5, 99, 3, 56))

print(set3)# {1, 3, 99, 5, 56}

set4 = set('hsghhhlll')

print(set4)# {'g', 'l', 's', 'h'}

6.9 集合生成式

(1){i for i in range(1, 10)}

6.9

set1 = {i for i in range(5)}

print(set1)# {0, 1, 2, 3, 4}

7. 元组

7.1 元组的特点

(1)元组是不可变序列,没有增删改操作

(2)直接使用小括号,小括号可以省略,但是不能省略逗号,因此只有一个元素时,也要加上逗号

7.1

tuple6 = (10, [10, 20], 30)

print(tuple6[0])# 10

print(tuple6[1])# [10, 20]

print(tuple6[2])#30

tuple6[1] = 200

print(tuple6)  #报错,因为元组是不可变序列

tuple6[1].append(30)

print(tuple6)# (10, [10, 20, 30], 30) #不报错,因为该元组的[1]是列表,列表是可变序列

7.2 元组的创建

(1)方式一:元组名=(值);空元组:元组名=()

(2)方式二:使用内置函数tuple():元组名=tuple((值));空元组:tuple()

7.2

tuple1 = ('AA', 'BB', 99)

print(tuple1)# ('AA', 'BB', 99)

print(type(tuple1))# <class 'tuple'>

tuple3 = 'AAB', 'BBb', 991

print(tuple3)# ('AAB', 'BBb', 991)

print(type(tuple3))# <class 'tuple'>

tuple4 = 'AA',   #若不使用逗号,会被当作str类型

print(tuple4)# ('AA',)

print(type(tuple4))# <class 'tuple'>

tuple2 = tuple(('2AA', '3BB', 299))

print(tuple2)# ('2AA', '3BB', 299)

print(type(tuple2))# <class 'tuple'>

tuple5 = ()

print(tuple5)# ()

print(type(tuple5))# <class 'tuple'>

7.3 元组的查询

(1)元组名[序号]

7.3

tuple6 = (10, [10, 20], 30)

print(tuple6[0])# 10

print(tuple6[1])# [10, 20]

print(tuple6[2])# 30

7.4 元组的遍历

(1)for item in 元组名

例7.4:

for item in tuple6:

    print(item)

8. 条件语句

8.1 单分支

(1)if condition1:

                  operation1

8.1

if 10 > 5:

        print('10>5')

8.2 双分支

(1)if condition1:

                operation1

        else:

                   operation2

8.2

if 10 > 5:

            print('10>5')

else:

        print('10<=5')

8.3 多分支

(1)if condition1:

                operation1

        elif condition2:

                operation2

        elif condition3:

                operation3

        [else:]

                [operation4]

8.4 嵌套分支

(1)if condition1:

                if condition3:

                        operation1

                else:

                        operation3

        else:

                operation2

9. for-in循环语句

(1)for 自定义变量 in 可迭代对象(如:字符串,list)

                循环体

(2)continue 跳出本次循环

(3)break 跳出本层循环

(4)注意: 若循环体中不需要用到自定义变量,可写成:_

9

for item in 'shdb':

    print(item)

for _ in 'agd':

    print('wo')

#输出100999之间的水仙花数(水仙花数:153 = 3*3*3 + 5*5*5 + 1*1*1

for i in range(100, 999):

    if i == ((i//100)**3 + ((i%100)//10)**3 + (i%10)**3):

        print(i)

10. 转义字符

10.1 制表符

(1)\t

10.1

import keyword

# 不同点:第一个 \t 占据3blank,第二个 \t 占据4blank

print('hello\tworld')# hello   world

print('helloooo\tword')# helloooo      word

10.2 换行符

(1)\n

10.2

print('hello\nworld')

10.3 回车

(1)\r :replace

10.3

print('hello\rworld')# world

10.4 撤销

(1)\b :back one space

10.4

print('hello\bworld')# hellworld

11. 运算符

11.1 算术运算符

(1)加法:+

(2)减法:-

(3)乘法:*(还可以用于字符串,例如“a"*5,就会显示aaaaa)

(4)除法:/

(5)整除://(一正一负向下取整)

(6)取余:%(公式:余数 = 被除数-除数*商)

(7)幂:**

(8)四舍五入取整:round

(9)向0取整:int

(10)向上取整:ceil

(11)向下取整:floor

11.1

print(1 + 1)#2

print(5 - 2)#3

print(2 * 2)#4

print(10 / 3)  # 3.3333333....

print(10 // 3)  # 3

print(-10 // -3) # 3

print(10 // -3) # -4

print(-10 // 3) # -4

print(10 % 3)  # 1

print(-10 % -3) # -1 

print(10 % -3) # -2

print(-10 % 3) # 2

print(2 ** 3) # 8

11.2 赋值运算符

(1)赋值:=

(2)自加:+=

(3)自减:-=

(4)自乘:*=

(5)自除:/=

(6)自整除://=

(7)自取余:%=

11.2

a = b = 20

print(a)#20

print(b)#20

a, b, c = 10, 20, 30 #the number of left and right must be equal

print(a)#10

print(b)#10

print(c)#30

a, b = 10, 20

a, b = b, a #exchange two value

print(a)#20

print(b)#10

a += 30

print(a)#50

a -= 10

print(a)#40

a *= 2

print(a)#80

a /= 5  # int---float

print(a)#16.0

a //= 5

print(a)#3.0

a %= 2

print(a)#1.0

11.3 比较运算符

(1)比较值(结果是bool):>   <   ==   >=   <=   !=

(2)比较标识(是否是同一个id,即是否是同一个对象):is/is not

11.3

a, b = 10, 20

print(a > b)

print(a < b)

print(a == b)

print(a >= b)

print(a <= b)

print(a != b)

a, b = 10, 10

print(a == b) # True

print(a is b) # True

print(a is not b) # False

print(id(a))

print(id(b))

list1 = [1, 2, 3, 4]

list2 = [1, 2, 3, 4]

print(list1 == list2) # True

print(list1 is list2) # False

print(list1 is not list2) # True

print(id(list1))

print(id(list2))

11.4 布尔运算符

(1)and

(2)or

(3)not

(4)in

(5)not in

11.4

print( 10 and 0) # 0

print(True and False)  # False

print(10 or 0) # 10

print(True or False)  # True

print(not 10)  # False

print(not False)  # True

print('a' in 'abcdef')  # True

print('a' not in 'abcdef')  # False

11.5 位运算符

(1)&

(2)|

(3)<<

(4)>>

11.5

print(4 & 5)  # 4

print(4 | 5)  # 5

print(4 << 2)  # 16

print(4 >> 2)  # 1

11.6 运算符优先级

(1)算术运算符>位运算符>比较运算符>布尔运算符>赋值运算符

(2)算术运算符中:(**)>(*,/,//,%)>(+,-)

(3)位运算符中:(<<,>>)>(&)>(|)

(4)比较运算符中:(>,<,==,>=,<=,!=)

(5)布尔运算符中:(and)>(or)

(6)有括号先算括号(优先级最高)

11.7 对数运算

(1)需要Import math包;求以2为底x的对数:math.log2(x)

12. 输入输出函数

12.1 输入函数input

(1)字符串变量 = input("提示信息:"):input输入的都是字符串

12.1

A = input('please input the first number:')

B = input('please input the second number:')

print('the sum of the two input number is:', int(A) + int(B))

12.2 输出函数print

(1)print():可输出数字/字符串/表达式/输出到文件

12.2

print(12.5)

print('ABC')

print("abc")

print(3+1)

fp = open('C:/Users/25030/Desktop/text.txt','a+') # a+: file not exist, creat; exsit, add

print('hello', file=fp)

fp.close()

  • 20
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值