Python入门

print("Hello World!")
  • 2. 数字

  • 2.1 取整

import math

s = '3.14159265'
f = float(s)  # string to float

# 不能把字符串转化为整形的数字
# a = int(s)
# print(a)

b = int(f)
print(b)  # 3

c = round(f, 3)  # 四舍五入,保留三位小数
print(c)  # 3.142

d = math.floor(f)
print(d)  # 3

e = math.ceil(f)
print(e)  # 4
  • 2.2 进制转换

a = hex(255)
print(a)  # 0xff
print(type(a))

b = oct(255)
print(b)  # 0o377
print(type(b))

c = bin(255)
print(c)  # 0b11111111
print(type(c))

d = pow(2, 3)  # 求幂
print(d)  # 8
print(type(d))
  • 2.3 求幂、类型转换

a = pow(2, 3)  # 求幂
print(a)  # 8

b = pow(2, 3, 3)  # 求幂后取余
print(b)  # 2

c = chr(97)  # ASCII to char
print(c)  # a

d = ord('a')  # char to ASCII
print(d)  # 97
  • 3. 序列(sequence)

  • 3.1 索引、切片、补零


# index1 -5 -4 -3 -2 -1
# index2  0  1  2  3  4
a_list = ['1', '2', '3', '4', '5']
# a_str = '12345'
list_len = len(a_list)

# [起始: 终止: 步长] 终点为终止位的前一位
a = a_list[0:-1]  # 到最后一位终止,终点为终止位的前一位
b = a_list[0:None]  # 无终止
c = a_list[None:None]  # 无起始,无终止
d = a_list[:]  # 无起始,无终止
e = a_list[::]  # 无起始,无终止
f = a_list[0:-1:2]  # 到最后一位终止,终点为终止位的前一位,步长为2
g = a_list[0:None:2]  # 无终止,步长为2
h = a_list[::-1]  # 无起始,无终止,步长为-1(index1),即反序 reversed()或 a_list.reverse()

'''
因为字符串不能改变,新获得的字符串是在释放原有字符串后新建的。因此不能直接对原始字符串中的某一位赋值,如: a[1] = '0'
整型的index为整型(int)的,字符串的index为字符型(chr)
'''
print(a)  # a_list: ['1', '2', '3', '4'], a_str: 1234
print(b)  # a_list: ['1', '2', '3', '4', '5'], a_str: 12345
print(c)  # a_list: ['1', '2', '3', '4', '5'], a_str: 12345
print(d)  # a_list: ['1', '2', '3', '4', '5'], a_str: 12345
print(e)  # a_list: ['1', '2', '3', '4', '5'], a_str: 12345
print(f)  # a_list: ['1', '3'], a_str: 13
print(g)  # a_list: ['1', '3', '5'], a_str: 135
print(h)  # a_list: ['5', '4', '3', '2', '1'], a_str: 54321

len_temp = len(f)
for index in a_list:
    if int(index) > len_temp:
        if int(index) <= list_len:
            f += '0'
print(f)  # a_list: ['1', '3', '0', '0', '0'], a_str: 13000
  •  3.2 len、enumerate、zip

a = 'python'
b = '1234567'

a_length = len(a)
print(a_length)  # 字符串的长度,6
print('\n')  # 换行。由于print自带一个换行,'\n'也是换行,所以输出结果是换两行

for index, value in enumerate(a):
    print(index, value)  # 按序成对输出元素及其对应索引
'''
0 p
1 y
2 t
3 h
4 o
5 n
'''

c = zip(b, a)  # 按序组成元素对
print(c, '\n')  # <zip object at 0x000001E453AC0608>
for p, q in c:
    print(p, q)  # 按序成对输出,若两字符串不等长,则输出对数按最短的字符串算
'''
1 p
2 y
3 t
4 h
5 o
6 n
'''
  • 3.3 reversed、append、extend

print('---------------------------------str' * 2)  # 连续输出字符串两次,中间无换行
a = 'abcdef'
for val in reversed(a):  # 逆序。适用于str类型
    print(val)
'''
f
e
d
c
b
a
'''

print('---------------------------------list' * 2)
a = [1, 2, 3, 4, 5, 6]
for val in reversed(a):  # 逆序。适用于list类型
    print(val)
'''
6
5
4
3
2
1
'''

print('---------------------------------append' * 2)
a = [1, 2, 3, 4, 5, 6]
b = []
for val in reversed(a):
    b.append(val)  # append后接列表中的元素
    print(b)  # 循环输出逆序拼接结果
'''
[6]
[6, 5]
[6, 5, 4]
[6, 5, 4, 3]
[6, 5, 4, 3, 2]
[6, 5, 4, 3, 2, 1]
'''

print('---------------------------------extend' * 2)
a = [1, 2, 3, 4, 5, 6]
a_len = len(a)
b = []
for index in range(0, a_len):  # index并不是列表的元素索引,而是列表元素的具体数值。可替换为任意变量,如:n
    b.extend([a[index]])   # extend后接列表
    print(b)
'''
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
'''
print('---------------------------------extend')
a = [1, 2, 3, 4, 5, 6]
a_len = len(a)
b = []
for n in range(0, a_len):
    b.extend([a[a_len-n-1]])  # 逆序
    print(b)
'''
[6]
[6, 5]
[6, 5, 4]
[6, 5, 4, 3]
[6, 5, 4, 3, 2]
[6, 5, 4, 3, 2, 1]
'''
  • 3.4 insert

print('---------------------------------insert_index=0' * 2)
a = [1, 2, 3, 4, 5, 6]
b = []
for val in a:
    b.insert(0, val)  # 索引为0,逆序
    print(b)  # 输出结果为逆序
'''
[1]
[2, 1]
[3, 2, 1]
[4, 3, 2, 1]
[5, 4, 3, 2, 1]
[6, 5, 4, 3, 2, 1]
'''

print('---------------------------------re_insert_index=0' * 2)
a = [1, 2, 3, 4, 5, 6]
b = []
for val in reversed(a):  # 逆序
    b.insert(0, val)  # 索引为0,逆序
    print(b)  # 两次逆序,输出结果为正序
'''
[6]
[5, 6]
[4, 5, 6]
[3, 4, 5, 6]
[2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
'''

print('---------------------------------insert_index>0' * 2)
a = [1, 2, 3, 4, 5, 6]
b = []
for val in a:
    b.insert(1, val)  # 索引大于0时(如:1),索引值之前的元素正序,之后的元素逆序
    print(b)
'''
[1]
[1, 2]
[1, 3, 2]
[1, 4, 3, 2]
[1, 5, 4, 3, 2]
[1, 6, 5, 4, 3, 2]
'''

print('---------------------------------re_insert_index>0' * 2)
a = [1, 2, 3, 4, 5, 6]
b = []
for val in reversed(a):
    b.insert(1, val)  # 有reversed,索引大于0时(如:1),索引值之前的元素逆序,之后的元素正序
    print(b)
'''
[6]
[6, 5]
[6, 4, 5]
[6, 3, 4, 5]
[6, 2, 3, 4, 5]
[6, 1, 2, 3, 4, 5]
'''
  • 4. 字符串(string)

  • 4.1 引号、换行

a = 'I love python'
b = "I don't love python"  # 双引号可包含单引号。其它一般情况下,双引号与单引号可互相替换
c = '''
I
love
python
'''  # 三个引号可包括换行符(第一行),此处也可用三个双引号
print(a, b, c)
'''
I love python I don't love python 
I
love
python
'''

# 前两种等价,换行后有空格;第三种换行后无空格
print('---------------------------------1')
a = 'I love python\n'
b = 'I love python'
print(a, b)
'''
I love python
 I love python
'''  # 换行后有空格

print('---------------------------------2')
a = 'I love python'
b = 'I love python'
print(a, '\n', b)
'''
I love python
 I love python
'''  # 换行后有空格

print('---------------------------------3')
a = 'I love python'
b = '\nI love python'
print(a, b)
'''
I love python 
I love python
'''  # 换行后无空格

# 此种换行不可行
'''
a = 'I love python'
b = 'I love python'
print(a, '\n'b)
'''
  • 4.2 字符串运算(+ 和 *)

a = 'I love python'
b = a + a  # 加号拼接中间无空格
c = a * 3  # 乘号重复中间无空格
print(a, '+++', b, '***', c)  # 各输出值之间有空格

a = 'I love python'
b = a + ' ' + a  # 加号拼接,中间添加空格
c = a * 3
print(a, '+++', b, '***', c)

a = 'I love python'
b = a + a
c = (a + ' ') * 3  # 添加空格,乘号重复
print(a, '+++', b, '***', c)

'''
I love python +++ I love pythonI love python *** I love pythonI love pythonI love python
I love python +++ I love python I love python *** I love pythonI love pythonI love python
I love python +++ I love pythonI love python *** I love python I love python I love python 
'''
  • 4.3 join

a = ['一', '整', '个', '都', '被', '你', '打', '败', '了', '啦', ]
# b = [1, 2, 3, 4, 5, 6]  # join 只能对str操作不能对int操作

c = ''.join(a)  # 拼接,双引号有相同作用
c_type = type(c)
print(c)  # 一整个都被你打败了啦
print(c_type)  # <class 'str'>

# 一口气全念对
a = '就让压力喘一口气给它机会跟着音乐'
c = "咪".join(a)
print(c)  # 就咪让咪压咪力咪喘咪一咪口咪气咪给咪它咪机咪会咪跟咪着咪音咪乐
  • 4.4 字符串格式化操作符(%)、补零(zfill、format)

a = 'I love %s and %s' % ('python', 'you')  # 按序排列
b = '\nI love %s' % 'python'
c = '\nMy name is %(name)s, and I am %(age)d years old' % {'age': 25, 'name': 'Mike'}  # 不需要按序排列
print(a, b, c)
'''
I love python and you 
I love python 
My name is Mike, and I am 25 years old
'''

# 补0
a = 12345
b = "%06d" % a  # 长6位,不足补零。输入整形,输出字符型
print(type(a))  # <class 'int'>
print(b)  # 012345
print(type(b))  # <class 'str'>

a = 12345
b = "%16d" % a
c = "%016d" % a
print(b)
print(c)
'''
           12345 b:输出为16位的字符串,不足默认补空格
0000000000012345 c:输出为16位的字符串,不足按设置补零
'''

a = 12345
b = str(a).zfill(6)  # 输入整形,输出字符型
print(b)  # 012345
print(type(b))  # <class 'str'>

# 转换为二进制数后补零至指定长度
a = 7
b = '{:06b}'.format(a)  # 输入整形,输出字符型
print(b)  # 012345
print(type(b))  # <class 'str'>

a = 7  # 上式的变形,适用于b为函数时
b = 0
for i in range(0, 4):
    b += i
    c = '{:0' + str(b) + 'b}'  # b=10
    d = c.format(a)
    print('b =', b, ', d =', d)
'''
b = 0 , d = 111
b = 1 , d = 111
b = 3 , d = 111
b = 6 , d = 000111
当格式化位数小于等于字符串位数,正常输出字符串
当格式化位数大于字符串位数,不足则补零
'''
  • 4.5 取消转义字符功能(r/R)、换行

print('This is a test of enter. \n')
print(r'This is a test of enter. \n')  # r:保持原样输出
print(R'This is a test of enter. \n')  # R:与r作用相同
'''
This is a test of enter. 

This is a test of enter. \n
This is a test of enter. \n
'''

print('1--------------')
print()  # 输出空白字符占一行
print('2--------------')
print('******')  # 输出字符串 ****** 占一行
print('3-------------- \n')
print('4--------------')
print('\n')  # print输出空白字符占一行,'\n'换行占一行,所以输出结果是空了两行
print('5--------------')
'''
1--------------

2--------------
******
3-------------- 

4--------------


5--------------
'''
  • 4.6 最值

a = 'abcdefg'
b = max(a)  # 按ASCII返回最大值
c = min(a)  # 按ASCII返回最小值
print('\n', a, '\n', b, '\n', c)  # 换行后有空格
'''
 abcdefg 
 g 
 a
'''  
  • 5. 列表(list)

  • 5.1 更改列表数据

"""
列表数据可变(序列/字符串数据不可变)。因此可通过列表对其中的对象进行修改以及增删
对于文字注释,最好使用三个双引号,而不是三个单引号
"""

a = 'abcdefg'
b = list(a)  # 把string转换成list
c = [1, 2, 3, 4, 5, 6, 7]
d = [a, b, c]
e = [0] * 5  # 初始化一定长度的list

print(a)  # abcdefg
print(b)  # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(c)  # [1, 2, 3, 4, 5, 6, 7]
print(d)  # ['abcdefg', ['a', 'b', 'c', 'd', 'e', 'f', 'g'], [1, 2, 3, 4, 5, 6, 7]]
print(e)  # [0, 0, 0, 0, 0]
  • 5.1 列表运算(+ 和 *)

a = 'abc'
b = list(a)  # 把string转换成列表
c = [1, 2, 3]
d = b + c  # 拼接两个list
e = c * 2  # 复制list后之后,把它们拼接在一起

print(a)  # abc
print(b)  # ['a', 'b', 'c']
print(c)  # [1, 2, 3]
print(d)  # ['a', 'b', 'c', 1, 2, 3]
print(e)  # [1, 2, 3, 1, 2, 3]
  • 5.2 append、extend、赋值(=)

a = [1, 2, 3]
b = ['a', 'b', 'c']

c = a.append(b)  # 接收的参数可以为任意类型,简单的追加到原list后。返回None
print(a)  # [1, 2, 3, ['a', 'b', 'c']]

d = a.extend(b)  # 接收的参数只能为list,将接收list中的元素添加到原list后。返回None
print(a)  # [1, 2, 3, ['a', 'b', 'c'], 'a', 'b', 'c']
print(c)  # None
print(d)  # None
'''
函数append和extend都是对list a本身操作,无返回结果。因此,c和d的值为None
'''

a = [1, 2, 3]
b = [0]

print(a)  # [1, 2, 3]

c = a  # 并不是为c开辟新的存储,而是把c与a看成同一变量
print(a)  # [1, 2, 3]
print(c)  # [1, 2, 3]

c.append(0)  # 对c操作也就是对a操作
print(a)  # [1, 2, 3, 0]
print(c)  # [1, 2, 3, 0]

c.extend(b)
print(a)  # [1, 2, 3, 0, 0]
print(c)  # [1, 2, 3, 0, 0]

c = [1, 2, 3]  # 对c重新赋值,为c开辟了新的存储,c与a不再是同一变量,对一个操作不会影响另一个
print(a)  # [1, 2, 3, 0, 0]
print(c)  # [1, 2, 3]

c.extend(b)
print(a)  # [1, 2, 3, 0, 0]
print(c)  # [1, 2, 3, 0]
  • 5.3 常用函数(count、index、insert、pop、remove、reserve、sort、sorted)

print('---------------------------------count'*2)
a = [1, 2, 3, 4, 5, 6, 1]
b = ['a', 'b', 'c', 'd', 'e', 'f', 'a']
c = a.count(1)  # 返回对象 1 在list a中出现的次数
d = b.count('a')  # 返回对象 'a' 在list b中出现的次数
print(c)  # 2
print(d)  # 2

print('---------------------------------index'*2)
a = [1, 2, 3, 4, 5, 6, 1]
b = ['a', 'b', 'c', 'd', 'e', 'f', 'a']
c = a.index(1)  # 返回对象 1 在list a中第一次出现的索引,索引从0开始
d = b.index('a')  # 返回对象 'a' 在list b中第一次出现的索引,索引从0开始
# e = b.index('m')  # 无匹配元素时报错
print(c)  # 0
print(d)  # 0

print('---------------------------------insert'*2)
a = [1, 2, 3, 4, 5, 6]
b = ['a', 'b', 'c', 'd', 'e', 'f']
c = a.insert(1, 0)  # 在索引为 1 的元素前插入对象 0。返回None
d = b.insert(1, 0)  # 在索引为 1 的元素前插入对象 0,插入的对象可以为任意类型。返回None
# e = b.index(100, 'm')  # 无匹配索引时报错
print(a)  # [1, 0, 2, 3, 4, 5, 6]
print(b)  # ['a', 0, 'b', 'c', 'd', 'e', 'f']
print(c)  # None
print(d)  # None

print('---------------------------------pop'*2)
a = [1, 2, 3, 4, 5, 6]
b = ['a', 'b', 'c', 'd', 'e', 'f']
c = a.pop()  # 未指定索引,删除列表最后一项,并返回该项的值。相当于从列表中取出该值
d = b.pop(1)  # 删除列表中索引为 1 的元素,并返回该项的值
# e = b.pop(100)  # 无匹配索引时报错
print(a)  # [1, 2, 3, 4, 5]
print(b)  # ['a', 'c', 'd', 'e', 'f']
print(c)  # 6
print(d)  # b

print('---------------------------------remove'*2)
a = [1, 2, 3, 4, 5, 6]
b = ['a', 'b', 'c', 'd', 'e', 'f']
c = a.remove(1)  # 删除列表中匹配对象 1 的第一个元素。返回None
d = b.remove('a')  # 删除列表中匹配对象 'a' 的第一个元素。返回None
# e = b.remove(100)  # 无匹配元素时报错
print(a)  # [2, 3, 4, 5, 6]
print(b)  # ['b', 'c', 'd', 'e', 'f']
print(c)  # None
print(d)  # None

print('---------------------------------reverse'*2)
a = [1, 2, 3, 4, 5, 6]
b = a.reverse()  # 对目标列表元素反序。返回None
# c = reversed(a)  # 用法错误
print(a)  # [6, 5, 4, 3, 2, 1]
print(b)  # None

print('---------------------------------sort'*2)
a = [1, 2, 3, 1, 2, 3]
b = ['a', 'b', 'c', 'a', 'b', 'c']
c = a.sort()  # 对目标列表元素升序排列。返回None
d = b.sort()  # 对目标列表元素升序排列。返回None
print(a)  # [1, 1, 2, 2, 3, 3]
print(b)  # ['a', 'a', 'b', 'b', 'c', 'c']
print(c)  # None
print(d)  # None

print('---------------------------------sorted'*2)
a = [1, 2, 3, 1, 2, 3]
b = ['a', 'b', 'c', 'a', 'b', 'c']
c = sorted(a)  # 对目标列表元素升序排列,返回排序后的值
d = sorted(b)  # 对目标列表元素升序排列,返回排序后的值
print(a)  # [1, 2, 3, 1, 2, 3]
print(b)  # ['a', 'b', 'c', 'a', 'b', 'c']
print(c)  # [1, 1, 2, 2, 3, 3]
print(d)  # ['a', 'a', 'b', 'b', 'c', 'c']
'''
# append + pop()  模拟堆栈,先进后出
# append + pop(0) 模拟队列,先进先出
'''
  • 5.4 赋值、浅拷贝、深拷贝

import copy

print('---------------------------------赋值'*2)
'''
赋值并不是为d开辟新的存储,而是把c与d看成同一变量
对c或d任一个操作也就是同时对两者操作
Python没有赋值,只有引用
'''
b = [0]
c = [1, 2, 3]
d = c
e = id(c)
f = id(d)
print('c    =', c)  # c    = [1, 2, 3]
print('d    =', d)  # d    = [1, 2, 3]
print('c_id =', e)  # c_id = 2448510866184
print('d_id =', f)  # d_id = 2448510866184
c.extend(b)
e = id(c)
f = id(d)
print('c    =', c)  # c    = [1, 2, 3, 0]
print('d    =', d)  # d    = [1, 2, 3, 0]
print('c_id =', e)  # c_id = 2448510866184
print('d_id =', f)  # d_id = 2448510866184

print('---------------------------------浅拷贝'*2)
c = [1, 2, 3]
c[1] = c  # 不可行
print('c =', c)  # c = [1, [...], 3]

print('---------------------------------浅拷贝-切片')
c = [1, 2, 3]
c[1] = c[:]  # 可行
print('c =', c)  # c = [1, [1, 2, 3], 3]

print('---------------------------------浅拷贝-list')
c = [1, 2, 3]
c[1] = list(c)  # 可行
print('c =', c)  # c = [1, [1, 2, 3], 3]

print('---------------------------------浅拷贝-copy')
c = [1, 2, 3]
c[1] = c.copy()  # 可行,且不用import copy模块
print('c =', c)  # c = [1, [1, 2, 3], 3]

print('---------------------------------浅拷贝-copy.copy')
c = [1, 2, 3]
c[1] = copy.copy(c)  # 可行
print('c =', c)  # c = [1, [1, 2, 3], 3]

print('---------------------------------浅拷贝-copy')
c = [1, 2, 3]
d = copy.copy(c)  # 可行
e = id(c)
f = id(d)
g = id(c[0])
h = id(d[0])
print('c     =', c)  # c     = [1, 2, 3]
print('d     =', d)  # d     = [1, 2, 3]
print('c_id  =', e)  # c_id  = 2667825191752
print('d_id  =', f)  # d_id  = 2667825191560
print('c0_id =', g)  # c0_id = 140704823878032
print('d0_id =', h)  # d0_id = 140704823878032

c[1] = copy.copy(c)
print('c    =', c)  # c    = [1, [1, 2, 3], 3]
print('c_id =', e)  # c_id = 2235996236104
d = copy.copy(c)
print('c    =', c)  # c    = [1, [1, 2, 3], 3]
print('d    =', d)  # d    = [1, [1, 2, 3], 3]
d[1][1] = 'a'
print('c    =', c)  # c    = [1, [1, 'a', 3], 3]
print('d    =', d)  # d    = [1, [1, 'a', 3], 3]
'''
虽然使用浅拷贝后c和d的id不一样了,但是c和d中嵌套结构(元素)的id还是相同的
当对c或d中嵌套结构的一个进行改变时,另一个也会随之改变
为避免这种情况,可以使用深拷贝
浅拷贝适用于不可变的对象(整数,实数,字符串等)
'''

print('---------------------------------深拷贝'*2)
c = [1, 2, 3]
c[1] = copy.copy(c)  # 可行
d = copy.deepcopy(c)  # 可行
e = id(c)
f = id(d)
g = id(c[1])
h = id(d[1])
print('c     =', c)  # c     = [1, [1, 2, 3], 3]
print('d     =', d)  # d     = [1, [1, 2, 3], 3]
print('c_id  =', e)  # c_id  = 2235996235912
print('d_id  =', f)  # d_id  = 2235996233928
print('c1_id =', g)  # c1_id = 2235996236104
print('d1_id =', h)  # d1_id = 2235996301384
# print('c[1][1] =', c[1][1])  # c[1][1] = 2
'''
综上,赋值后,列表id相同,列表中元素id相同,且嵌套结构的id也相同
对其中一个列表操作,相当于同时对另一个列表操作

浅拷贝后,列表id不同,列表中元素id相同,且嵌套结构的id也相同。即,不同的列表标签指向相同的元素集合
对其中一个列表非嵌套元素操作,只改变了该列表标签对应的元素集合,而不改变另一个标签对应的元素集合
对其中一个列表的嵌套元素操作,相当于同时对另一个列表中相应的嵌套元素操作(对应于赋值)

深拷贝后,列表id不同,列表中元素id相同,但嵌套结构的id不相同
对其中一个列表非嵌套元素操作,只改变了该列表标签对应的元素集合,而不改变另一个标签对应的元素集合
对其中一个列表的嵌套元素操作,另一个列表中相应的嵌套元素不发生改变(对应于浅拷贝)

----------------------增强赋值与共享引用-------------------------------------
x = x + y,x 出现两次,必须执行两次,性能不好,合并必须新建对象 x,然后复制两个列表合并属于复制/拷贝
x += y,x 只出现一次,也只会计算一次,性能好,不生成新对象,只在内存块末尾增加元素
当 x、y 为list时, += 会自动调用 extend ,属于共享引用
'''
  • 5.5 推导、解析(reduce、map、filter)

import functools

a = [1, 2, 3, 4, 5, 6, 7]
b = [x * 2 for x in a]  # 对列表中的每一个元素进行操作

print(a)  # [1, 2, 3, 4, 5, 6, 7]
print(b)  # [2, 4, 6, 8, 10, 12, 14]

a = [1, 2, 3]
for x in map(bin, a):
    print(x)
'''
0b1
0b10
0b11
'''

a = [1, 2, 3]
b = [bin(x) for x in a]
print(b)  # ['0b1', '0b10', '0b11']


def add(x, y):  # 与其他语句间隔两行
    return x + y


a = [1, 2, 3, 4, 5]           # a中至少要有两个元素
b = functools.reduce(add, a)  # 对a的前两个元素执行加操作,把返回的值与第三个元素执行加操作,最终完成a中元素的叠加
print(b)        # 15
print(type(b))  # <class 'int'>

a = ['H', 'e', 'l', 'l', 'o']  # 对chr型数据也成立
b = functools.reduce(add, a)   # 对于chr型的 + ,就是字符连接
print(b)        # Hello
print(type(b))  # <class 'str'>

a = ['H', 'e', 'l', 'l', 'o', ' ']
b = ['W', 'o', 'r', 'l', 'd', '!']
a.extend(b)
c = functools.reduce(add, a)
print(c)  # Hello World!


def foo(x):
    return 'love' in x


a = ['love', 'hate', 'I love Python', 'I love you']
for x in map(foo, a):  # 使用map来检测函数的返回值
    print(x)           # foo返回的是True/False
'''
True
False
True
True
'''

for x in filter(foo, a):  # filter筛选出foo返回的布尔值为True的元素
    print(x)
'''
love
I love Python
I love you
'''

for x in filter(None, a):  # 若函数为None,则返回所有值
    print(x)
'''
love
hate
I love Python
I love you
'''
  • 5.6 range

print(range(0, 10))        # range(0, 10) 返回range类型
print(list(range(0, 10)))  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 返回列表,数值范围为起始位到截止位的前一位
print(list(range(10)))     # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 与上一语句等价
  • 6. tuple

# 创建tuple的两种方式
a = tuple('abc')  # tuple是不可变的list,一旦创建,就不能改变它
b = ('a', 'b', 'c')
print(a)  # ('a', 'b', 'c')
print(b)  # ('a', 'b', 'c')

print(b[0])    # a 当对tuple切片时,会产生一个新的tuple。只有一个元素的tuple不带括号
print(b[-1])   # c
print(b[1:3])  # ('b', 'c') 到第四个元素的的前一个元素,该元素是存在的,因此没有报错

print(a.count('a'))  # 1 tuple中有一个 'a'
print(a.index('a'))  # 0 tuple中'a'的索引值为0

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

a[2][0] = 5  # 当tuple中嵌套可变结构时,该结构内的元素可变
print(a)  # (1, 2, [5, 4], 5)
'''
使用Tuple的好处:
1.Tuple比list操作速度快。如果定义了一个值的常量集,并且唯一要用它做的是不断地遍历它, 就使用tuple代替list
2.对不需要修改的数据进行“写保护”,可以使代码更安全
  使用tuple而不是list如同拥有一个隐含的assert语句,说明这一数据是常量
  如果必须要改变这些值, 则需要执行tuple到list的转换
3.Tuple可以作为Dictionary的Key,但是List不可以
4.Tuple可以用作字符串格式化
'''

a = ('a', 'b', 'c')
print(a)  # ('a', 'b', 'c')

b = list(a)  # 并不是对a本身转换,而是把转换后的值放入新的list中
print(a)  # ('a', 'b', 'c')
print(b)  # ['a', 'b', 'c']

c = tuple(b)  # 并不是对b本身转换,而是把转换后的值放入新的tuple中
print(a)  # ('a', 'b', 'c')
print(b)  # ['a', 'b', 'c']
print(c)  # ('a', 'b', 'c')
print(id(a))  # 1411470170056
print(id(b))  # 1411470364552
print(id(c))  # 1411470022840

# a = ('abc') # 此处会提示括号是多余的,因为当括号内仅有一个元素时,该变量是str而不是tuple的
b = ('abc',)  # 只有当括号内至少有两个元素时,该变量才是tuple的
# print(type(a))
print(type(b))  # <class 'tuple'>
  • 7. 字典(dictionary)

  • 7.1 创建

# 创建dict
a = {'H': 'Hello', 'W': 'World'}
b = dict(zip(['H', 'W'], ['Hello', 'World']))
c = dict(H='Hello', W='World')  # 等号两端不能有空格
d = {x: x for x in range(0, 4)}  # 新建dict

print(a)  # {'H': 'Hello', 'W': 'World'}
print(b)  # {'H': 'Hello', 'W': 'World'}
print(c)  # {'H': 'Hello', 'W': 'World'}
print(d)  # {0: 0, 1: 1, 2: 2, 3: 3}

print(a['H'])  # Hello
print(a['W'])  # World
print(a['H'], a['W'])  # Hello World
# print(a[0])    # 报错,因为不存在该索引
# print(a['M'])  # 报错,因为不存在该索引
  • 7.2 操作(修改、添加、删除、清空)

a = {'H': 'Hello', 'W': 'World'}
print(a)  # {'H': 'Hello', 'W': 'World'}

a['W'] = 'Wow'  # 修改索引对应内容
print(a)  # {'H': 'Hello', 'W': 'Wow'}

'''
若无对应索引,则添加
索引对应内容可为任意类型
'''
a['str'] = 'wow'
print(a)  # {'H': 'Hello', 'W': 'Wow', 'str': 'wow'}
a['int'] = 30
print(a)  # {'H': 'Hello', 'W': 'Wow', 'str': 'wow', 'int': 30}
a['list'] = [30, 40]
print(a)  # {'H': 'Hello', 'W': 'Wow', 'str': 'wow', 'int': 30, 'list': [30, 40]}
a['tuple'] = ('a', 'b', 'c')
print(a)  # {'H': 'Hello', 'W': 'Wow', 'str': 'wow', 'int': 30, 'list': [30, 40], 'tuple': ('a', 'b', 'c')}

a = {'H': 'Hello', 'W': 'World'}
a[30] = 40  # 索引可为str/int
print(a)  # {'H': 'Hello', 'W': 'World', 30: 40}

del a[30]  # 删除目标索引及其对应内容
print(a)  # {'H': 'Hello', 'W': 'World'}

a.clear()  # 清空dictionary
print(a)  # {}
  • 7.3 遍历、拷贝

a = {'H': 'Hello', 'W': 'World'}
for key in a:
    print(key, a[key])
'''
H Hello
W World
'''

b = dict(**a)  # 解析,把a中元素取映射到b中
c = a.copy()  # 等价于浅拷贝c = copy.copy(a),需要先import copy
print(b)  # {'H': 'Hello', 'W': 'World'}
print(c)  # {'H': 'Hello', 'W': 'World'}
print(id(a))       # 1788888757016
print(id(b))       # 1788889089512
print(id(c))       # 1788888757096
print(id(a['H']))  # 1788888800240
print(id(b['H']))  # 1788888800240
print(id(c['H']))  # 1788888800240
  • 7.4 常用函数(update、fromkeys、setdefault、keys、values、items、enumerate)

a = {'H': 'Hello', 'W': 'World'}
b = {'H': 'Hi', 'L': 'Little', 'P': 'Prince'}

print('---------------------------------update' * 2)
c = a.update(b)  # 把b中的元素复制到a中。若有相同的key,则覆盖对应的key值;若没有,则扩展。返回None
print(a)  # {'H': 'Hi', 'W': 'World', 'L': 'Little', 'P': 'Prince'}
print(b)  # {'H': 'Hi', 'L': 'Little', 'P': 'Prince'}
print(c)  # None

print('---------------------------------fromkeys' * 2)
a = {}.fromkeys(('m', 'n'), 3)  # 创建有相同key值的dict
print(a)  # {'m': 3, 'n': 3}

print('---------------------------------setdefault' * 2)
a.setdefault('o', {})['x'] = 4  # 为a添加新的项,key为'o',key值为空dict{},并为空dict添加一个元素'x': 3
print(a)  # {'m': 3, 'n': 3, 'o': {'x': 4}}

a.setdefault('p', []).append('x')  # 为a添加新的项,key为'p',key值为空list[],并为空list添加一个元素'x'
print(a)  # {'m': 3, 'n': 3, 'o': {'x': 4}, 'p': ['x']}

print('---------------------------------keys' * 2)
a = {'m': 3, 'n': 3, 'o': {'x': 4}, 'p': ['x']}
b = a.keys()  # 获取字典的key列表。当字典较大的时候占用大量内存
print(b)  # dict_keys(['m', 'n', 'o', 'p'])
print(type(b))  # <class 'dict_keys'>

print('---------------------------------values' * 2)
a = {'m': 3, 'n': 3, 'o': {'x': 4}, 'p': ['x']}
b = a.values()  # 获取字典的value值列表。当字典较大的时候占用大量内存
print(b)  # dict_values([3, 3, {'x': 4}, ['x']])

print('---------------------------------items' * 2)
a = {'m': 3, 'n': 3, 'o': {'x': 4}, 'p': ['x']}
b = a.items()  # 获取字典的list,list的元素为字典key与key值组成的tuple对。当字典较大的时候占用大量内存
print(b)  # dict_items([('m', 3), ('n', 3), ('o', {'x': 4}), ('p', ['x'])])

print('---------------------------------enumerate' * 2)
a = {'m': 3, 'n': 3, 30: {'x': 4}, 40: ['x']}
b = enumerate(a)  # 获取字典的迭代器,配合next获取索引和key值构成的tuple对象。当超出索引时报错
print(b)  # <enumerate object at 0x000001CEB23F8098>
print(next(b))  # (0, 'm')
print(next(b))  # (1, 'n')
print(next(b))  # (2, 30)
print(next(b))  # (3, 40)
# print(next(b)) 报错

for index, key in enumerate(a):
    print(index, key)  # 按序成对输出元素及其对应索引
    print(type(index), type(key))
'''
0 m
<class 'int'> <class 'str'>
1 n
<class 'int'> <class 'str'>
2 30
<class 'int'> <class 'int'>
3 40
<class 'int'> <class 'int'>
'''
  • 7.5 排序(sort)

# Python3中,dict.keys(),dict.items(),dict.values()不会再返回列表.因此要先把这些值转化为list才能进行sort


def dict_sort_key(a):
    b = a.keys()
    c = list(b)
    c.sort()
    return [a[key] for key in c]


def dict_sort_value(a):
    b = a.items()
    c = list(b)
    c.sort()
    return [value for key, value in c]


def dict_sort(a):
    b = a.items()
    c = list(b)
    c.sort()
    return [dict(c)]


z = {'p': 'p', 'm': 'm', 'n': 'n', 'o': 'o'}
print(dict_sort_key(z))  # ['m', 'n', 'o', 'p']
print(dict_sort_value(z))  # ['m', 'n', 'o', 'p']
print(dict_sort(z))  # [{'m': 'm', 'n': 'n', 'o': 'o', 'p': 'p'}]
  • 7.6 通过解析新建

a = [1, 2, 3, 4, 5]
b = [x % 2 == 0 for x in a]  # 解析list,返回布尔值列表
c = [x + 1 for x in a]  # 解析list,返回int列表
print(a)  # [1, 2, 3, 4, 5]
print(b)  # [False, True, False, True, False]
print(c)  # [2, 3, 4, 5, 6]

a = {x: x for x in range(0, 4)}  # 新建dict
b = {x: x % 2 == 0 for x in range(0, 4)}  # 新建dict
c = {x: x + 1 for x in range(0, 4)}  # 新建dict
print(a)  # {0: 0, 1: 1, 2: 2, 3: 3}
print(b)  # {0: True, 1: False, 2: True, 3: False}
print(c)  # {0: 1, 1: 2, 2: 3, 3: 4}
  • 8. 集合(set)

  • 8.1 创建

a = list(range(0, 5))
b = set(a)  # 把list转化为set
c = set()  # 新建空的set,dict用的{},set用的()。虽然得到的都是{},但是类型不同

print(a)        # [0, 1, 2, 3, 4]
print(type(a))  # <class 'list'>
print(b)        # {0, 1, 2, 3, 4}
print(type(b))  # <class 'set'>
print(c)        # set()
print(type(b))  # <class 'set'>
  • 8.2 增删(append、extend)

a = list(range(0, 5))
a.append(6)
b = set(a)
print(a)  # [0, 1, 2, 3, 4, 6]
print(b)  # {0, 1, 2, 3, 4, 6}

a = list(range(0, 5))
a.append([6, 7])
print(a)  # [0, 1, 2, 3, 4, [6, 7]]
# b = set(a)
# print(b)  # 当在列表中新加列表元素,再使用这个列表构造set会失败

print('---------------------------------')
a = list(range(0, 5))
a.extend([6, 7])
b = set(a)
print(a)  # [0, 1, 2, 3, 4, 6, 7]
print(b)  # {0, 1, 2, 3, 4, 6, 7} 可使用extend扩展元素

print('---------------------------------')
a = list(range(0, 5))
# a.extend([[6, 7], [8, 9]])
b = set(a)
print(a)  # [0, 1, 2, 3, 4]
# print(b)  # 可使用extend扩展元素,但如果元素为列表,则报错
  • 8.3 增删(add、frozenset)

a = list(range(1, 5))
b = set(a)
b.add(0)  # 在set最前面添加
print(a)  # [1, 2, 3, 4]
print(b)  # {0, 1, 2, 3, 4}

print('---------------------------------')
c = frozenset(b)
print(c)  # frozenset({0, 1, 2, 3, 4})
# c.add(0)  # 报错
# print(c)  

d = set(c)
print(d)  # {0, 1, 2, 3, 4}

d = list(c)
print(d)  # [0, 1, 2, 3, 4]
'''
frozenset不能更改元素,但可以通过转换为set或list进行更改。类似于tuple
优点也相似于tuple,起到写保护的作用
'''
  • 8.4 消重

d = [0, 1, 1, 2] * 3
e = set(d)  # set中的元素应互不相同,使用该方法可以对list快速消重
print(d)  # [0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2]
print(e)  # {0, 1, 2}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值