14dayPythonTask4-列表元组字符串

列表

列表的创建

x = list(range(10, 1, -2))
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>
  • 创建二维数组
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]]
print(x, type(x))
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]] <class 'list'>

【注意】

x = [a] * 4操作中,只是创建4个指向list的引用,所以一旦a改变,x中4个a也会随之改变。

x = [[0] * 3] * 4
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>

x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>

a = [0] * 3
x = [a] * 4
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>

x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>

列表不像元组(tuple),列表内容可更改 (mutable),因此附加 (append, extend)、插入 (insert)、删除 (remove, pop) 这些操作都可以用在它身上。

expend 、append、insert、remove、pop

注意:上述操作都是在原list对象上使用的,无返回值

  • list.append(obj) 在列表末尾添加新的对象,只接受一个参数,参数可以是任何数据类型,被追加的元素在 list 中保持着原结构类型。
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.append(['Thursday', 'Sunday'])
print(x)  
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', ['Thursday', 'Sunday']]

print(len(x))  # 6
  • list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.extend(['Thursday', 'Sunday'])
print(x)  
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday', 'Sunday']

print(len(x))  # 7
  • 严格来说 append 是追加,把一个东西整体添加在列表后,而 extend 是扩展,把一个东西里的所有元素添加在列表后。

  • list.insert(index, obj) 在编号 index 位置插入 obj

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.insert(2, 'Sunday')
print(x)
# ['Monday', 'Tuesday', 'Sunday', 'Wednesday', 'Thursday', 'Friday']

print(len(x))  # 6
  • list.remove(obj) 移除列表中某个值的第一个匹配项
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.remove('Monday')
print(x)  # ['Tuesday', 'Wednesday', 'Thursday', 'Friday']
  • list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值,注意,pop一个list之后,在list本身上发生修改
  • removepop 都可以删除元素,前者是指定具体要删除的元素,后者是指定一个索引。
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
y = x.pop()
print(y)  # Friday

y = x.pop(0)
print(y)  # Monday

y = x.pop(-2)
print(y)  # Wednesday
print(x)  # ['Tuesday', 'Thursday']
  • del var1[, var2 ……] 删除单个或多个对象。
  • 如果知道要删除的元素在列表中的位置,可使用del语句。
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
del x[0:2]
print(x)  # ['Wednesday', 'Thursday', 'Friday']

如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句;如果你要在删除元素后还能继续使用它,就使用方法pop()

获取list中的元素

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:4:2])  # ['Tuesday', 'Thursday']
print(week[:4:2])  # ['Monday', 'Wednesday']
print(week[1::2])  # ['Tuesday', 'Thursday']
print(week[::-1])  
# ['Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday']

深拷贝、浅拷贝

参考:https://blog.csdn.net/wuzhongqiang/article/details/106490041

深拷贝:与原集合彻底无关联

浅拷贝:与原集合的最外面一层没有关联,但是对于list中的list是指向的同一块内存

【浅拷贝例子】

# 再创建一个新的列表,也是列表套列表
a = [1, 2, [3, 4, 5]]
ac = a.copy()   # ac是a的一个浅拷贝

# 我们改一下ac的值
ac[0] = 10   
print(a[0], ac[0])   # 1 10    确实实现了拷贝, a和ac分开了

# 但是真的分的彻底吗?  我们改一下ac的值,但这次该里面那个列表
ac[2][1] = 40
print(a[2][1], ac[2][1]) # 40 40 我们发现了啥?  竟然改ac里面列表的时候a里面的列表也跟着变了

浅拷贝

【深拷贝例子】

from copy import deepcopy

a = [1, 2, [3, 4, 5]]
ac = deepcopy(a)
ac[0] = 10
ac[2][1] = 40
print(a[0], ac[0])   # 1 10 
print(ac[2][1], a[2][1])    # 40 4

深拷贝例子

【例子】

list1 = [[123, 456], [789, 213],3]
list2 = list1       		# 完全一样,始终指向同一块内存
list3 = list1[:]          	# 浅拷贝

print('list1:{}'.format(id(list1)))         
print(id(list2))
print(id(list3))
print('****')
list1[0][0]=111
print('list1:{}'.format(list1))
print('list2:{}'.format(list2))
print('list3:{}'.format(list3))

print("----")
list1[2]=2
print('list1:{}'.format(list1))         #  [[123, 456], [789, 213],2]
print('list2:{}'.format(list2))         #  [[123, 456], [789, 213],2]
print('list3:{}'.format(list3))         #  [[123, 456], [789, 213],3]

列表的常用操作符

【注意】

前面三种方法(append, extend, insert)可对列表增加元素,它们没有返回值,是直接修改了原数据对象。 而将两个list相加,需要创建新的 list 对象,从而需要消耗额外的内存,特别是当 list 较大时,尽量不要使用 “+” 来添加list。

练习题

# list
def test1():
    lst= [2, 5, 6, 7, 8, 9, 2, 9, 9]
    print('1:{}'.format(lst))
    lst.append(15)
    print('2:{}'.format(lst))

    lst.insert(len(lst)//2,20)
    print('3:{}'.format(lst))


    lst.extend(list((2,5,6)))
    print('4:{}'.format(lst))


    lst.pop(3)
    print('5:{}'.format(lst))
    print('***')

    lst.reverse()
    print('6:{}'.format(lst))
    lst6=lst[::-1]      # start,end,step
    print('6:{}'.format(lst6))
    print('***')

    lst.sort(reverse=False)
    print('7:{}'.format(lst))
    lst.sort(reverse=True)
    print('8:{}'.format(lst))


def test2():
    lst = [1, [4, 6], True]
    for i in range(len(lst)):
        if str(lst[i]).isdigit():
            lst[i] = int(lst[i]*2)
        else:
            lst[i] =lst[i]
    # ans=[i*2 for i in lst if str(i).isdigit() else  ]
    print(lst)

元组

创建和访问一个元组

  • Python 的元组与列表类似,不同之处在于tuple被创建后就不能对其进行修改,类似字符串。
  • 元组使用小括号,列表使用方括号。
  • 元组与列表类似,也用整数来对它进行索引 (indexing) 和切片 (slicing)。
  • 创建元组可以用小括号 (),也可以什么都不用,为了可读性,建议还是用 ()。
  • 元组中只包含一个元素时,需要在元素后面添加逗号,否则括号会被当作运算符使用。

【创建二维元组】

x = (1, 10.31, 'python'), ('data', 11)
print(x)
# ((1, 10.31, 'python'), ('data', 11))

print(x[0])
# (1, 10.31, 'python')
print(x[0][0], x[0][1], x[0][2])
# 1 10.31 python

print(x[0][0:2])
# (1, 10.31)

更新和删除一个元组

元组有不可更改 (immutable) 的性质,因此不能直接给元组的元素赋值,但是只要元组中的元素可更改 (mutable),那么我们可以直接更改其元素,注意这跟赋值其元素不同。

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

t1[3][0] = 9
print(t1)  # (1, 2, 3, [9, 5, 6])

内置方法

元组大小和内容都不可更改,因此只有 countindex 两种方法。

t = (1, 10.31, 'python')
print(t.count('python'))  # 1
print(t.index(10.31))  # 1
  • count('python') 是记录在元组 t 中该元素出现几次,显然是 1 次
  • index(10.31) 是找到该元素在元组 t 的索引,显然是 1

解压元组

读取元组中的元素

  • 解压(unpack)一维元组(有几个元素左边括号定义几个变量)
t = (1, 10.31, 'python')
(a, b, c) = t
print(a, b, c)
# 1 10.31 python
  • 解压二维元组(按照元组里的元组结构来定义变量)
t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python
  • 如果你只想要元组其中几个元素,用通配符「*」,英文叫 wildcard,在计算机语言中代表一个或多个元素。下例就是把多个元素丢给了 rest 变量。
t = 1, 2, 3, 4, 5
a, b, *rest, c = t
print(a, b, c)  # 1 2 5
print(rest)  # [3, 4]
  • 如果你根本不在乎 rest 变量,那么就用通配符「*」加上下划线「_」。
t = 1, 2, 3, 4, 5
a, b, *_ = t
print(a, b)  # 1 2

练习题

1、元组概念

写出下面代码的执行结果和最终结果的类型

(1, 2)*2
(1, )*2
(1)*2

分析为什么会出现这样的结果.

答:

In [2]: (1,2)*2
Out[2]: (1, 2, 1, 2)

In [3]: (1, )*2
Out[3]: (1, 1)

In [4]: (1)*2
Out[4]: 2

2、拆包过程是什么?

a, b = 1, 2

上述过程属于拆包吗?

可迭代对象拆包时,怎么赋值给占位符?

答:

In [8]: a,*r,b=(1,22,23,4)

In [9]: a
Out[9]: 1

In [10]: r
Out[10]: [22, 23]

In [11]: type(r)
Out[11]: list

In [12]: b
Out[12]: 4

可迭代对象unpack时,按照对应的结构来对应赋值。

字符串

1. 字符串的定义

  • Python 中字符串被定义为引号之间的字符集合。
  • Python 支持使用成对的 单引号 或 双引号。
  • Python 的常用转义字符
转义字符描述
\\反斜杠符号
\'单引号
\"双引号
\n换行
\t横向制表符(TAB)
\r回车
  • 原始字符串只需要在字符串前边加一个英文字母 r 即可。
print(r'C:\Program Files\Intel\Wifi\Help')  
# C:\Program Files\Intel\Wifi\Help

2. 字符串的切片与拼接

  • 类似于元组具有不可修改性
  • 从 0 开始 (和 Java 一样)
  • 切片通常写成 start:end 这种形式,包括「start 索引」对应的元素,不包括「end索引」对应的元素。
  • 索引值可正可负,正索引从 0 开始,从左往右;负索引从 -1 开始,从右往左。使用负数索引时,会从最后一个元素开始计数。最后一个元素的位置编号是 -1。
str1 = 'I Love LsgoGroup'
print(str1[:6])  # I Love
print(str1[5])  # e
print(str1[:6] + " 插入的字符串 " + str1[6:])  
# I Love 插入的字符串  LsgoGroup

s = 'Python'
print(s)  # Python
print(s[2:4])  # th
print(s[-5:-2])  # yth
print(s[2])  # t
print(s[-1])  # n

3. 字符串的常用内置方法

  • capitalize() 将字符串的第一个字符转换为大写。
str2 = 'xiaoxie'
print(str2.capitalize())  # Xiaoxie
  • lower() 转换字符串中所有大写字符为小写。
  • upper() 转换字符串中的小写字母为大写。
  • swapcase() 将字符串中大写转换为小写,小写转换为大写。
str2 = "DAXIExiaoxie"
print(str2.lower())  # daxiexiaoxie
print(str2.upper())  # DAXIEXIAOXIE
print(str2.swapcase())  # daxieXIAOXIE
  • count(str, beg= 0,end=len(string)) 返回str在 string 里面出现的次数,如果beg或者end指定则返回指定范围内str出现的次数。
str2 = "DAXIExiaoxie"
print(str2.count('xi'))  # 2
  • endswith(suffix, beg=0, end=len(string)) 检查字符串是否以指定子字符串 suffix 结束,如果是,返回 True,否则返回 False。如果 begend 指定值,则在指定范围内检查。
  • startswith(substr, beg=0,end=len(string)) 检查字符串是否以指定子字符串 substr 开头,如果是,返回 True,否则返回 False。如果 begend 指定值,则在指定范围内检查。
str2 = "DAXIExiaoxie"
print(str2.endswith('ie'))  # True
print(str2.endswith('xi'))  # False
print(str2.startswith('Da'))  # False
print(str2.startswith('DA'))  # Tru
  • find(str, beg=0, end=len(string)) 检测 str 是否包含在字符串中,如果指定范围 begend,则检查是否包含在指定范围内,如果包含,返回开始的索引值,否则返回 -1。
  • rfind(str, beg=0,end=len(string)) 类似于 find() 函数,不过是从右边开始查找。
str2 = "DAXIExiaoxie"
print(str2.find('xi'))  # 5
print(str2.find('ix'))  # -1
print(str2.rfind('xi'))  # 9
  • isnumeric() 如果字符串中只包含数字字符,则返回 True,否则返回 False。
str3 = '12345'
print(str3.isnumeric())  # True
str3 += 'a'
print(str3.isnumeric())  # False
  • ljust(width[, fillchar])返回一个原字符串左对齐,并使用fillchar(默认空格)填充至长度width的新字符串。
  • rjust(width[, fillchar])返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度width的新字符串。
str4 = '1101'
print(str4.ljust(8, '0'))  # 11010000
print(str4.rjust(8, '0'))  # 00001101
  • lstrip([chars]) 截掉字符串左边的空格或指定字符。
  • rstrip([chars]) 删除字符串末尾的空格或指定字符。
  • strip([chars]) 在字符串上执行lstrip()rstrip()
str5 = ' I Love LsgoGroup '
print(str5.lstrip())  # 'I Love LsgoGroup '
print(str5.lstrip().strip('I'))  # ' Love LsgoGroup '
print(str5.rstrip())  # ' I Love LsgoGroup'
print(str5.strip())  # 'I Love LsgoGroup'
print(str5.strip().strip('p'))  # 'I Love LsgoGrou'
  • partition(sub) 找到子字符串sub,把字符串分为一个三元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回('原字符串','','')
  • rpartition(sub)类似于partition()方法,不过是从右边开始查找。

【例子】

str5 = ' I Love LsgoGroup '
print(str5.strip().partition('o'))  # ('I L', 'o', 've LsgoGroup')
print(str5.strip().partition('m'))  # ('I Love LsgoGroup', '', '')
print(str5.strip().rpartition('o'))  # ('I Love LsgoGr', 'o', 'up')
  • replace(old, new [, max]) 把 将字符串中的old替换成new,如果max指定,则替换不超过max次。

【例子】

str5 = ' I Love LsgoGroup '
print(str5.strip().replace('I', 'We'))  # We Love LsgoGroup
  • split(str="", num) 不带参数默认是以空格为分隔符切片字符串,如果num参数有设置,则仅分隔num个子字符串,返回切片后的子字符串拼接的列表。

【例子】

str5 = ' I Love LsgoGroup '
print(str5.strip().split())  # ['I', 'Love', 'LsgoGroup']
print(str5.strip().split('o'))  # ['I L', 've Lsg', 'Gr', 'up']

【例子】

u = "www.baidu.com.cn"
# 使用默认分隔符
print(u.split())  # ['www.baidu.com.cn']

# 以"."为分隔符
print((u.split('.')))  # ['www', 'baidu', 'com', 'cn']

# 分割0次
print((u.split(".", 0)))  # ['www.baidu.com.cn']

# 分割一次
print((u.split(".", 1)))  # ['www', 'baidu.com.cn']

# 分割两次
print(u.split(".", 2))  # ['www', 'baidu', 'com.cn']

# 分割两次,并取序列为1的项
print((u.split(".", 2)[1]))  # baidu

# 分割两次,并把分割后的三个部分保存到三个变量
u1, u2, u3 = u.split(".", 2)
print(u1)  # www
print(u2)  # baidu
print(u3)  # com.cn

【例子】去掉换行符

c = '''say
hello
baby'''

print(c)
# say
# hello
# baby

print(c.split('\n'))  # ['say', 'hello', 'baby']

【例子】

string = "hello boy<[www.baidu.com]>byebye"
print(string.split('[')[1].split(']')[0])  # www.baidu.com
print(string.split('[')[1].split(']')[0].split('.'))  # ['www', 'baidu', 'com']
  • splitlines([keepends]) 按照行(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数keepends为 False,不包含换行符,如果为 True,则保留换行符。

【例子】

str6 = 'I \n Love \n LsgoGroup'
print(str6.splitlines())  # ['I ', ' Love ', ' LsgoGroup']
print(str6.splitlines(True))  # ['I \n', ' Love \n', ' LsgoGroup']
  • maketrans(intab, outtab) 创建字符映射的转换表,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
  • translate(table, deletechars="") 根据参数table给出的表,转换字符串的字符,要过滤掉的字符放到deletechars参数中。

【例子】

str7 = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str7.maketrans(intab, outtab)
print(trantab)  # {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}
print(str7.translate(trantab))  # th3s 3s str3ng 2x1mpl2....w4w!!!

4. 字符串格式化

  • format 格式化函数

【例子】

str8 = "{0} Love {1}".format('I', 'Lsgogroup')  # 位置参数
print(str8)  # I Love Lsgogroup

str8 = "{a} Love {b}".format(a='I', b='Lsgogroup')  # 关键字参数
print(str8)  # I Love Lsgogroup

str8 = "{0} Love {b}".format('I', b='Lsgogroup')  # 位置参数要在关键字参数之前
print(str8)  # I Love Lsgogroup

str8 = '{0:.2f}{1}'.format(27.658, 'GB')  # 保留小数点后两位
print(str8)  # 27.66GB
  • Python 字符串格式化符号
符 号描述
%c格式化字符及其ASCII码
%s格式化字符串,用str()方法处理对象
%r格式化字符串,用rper()方法处理对象
%d格式化整数
%o格式化无符号八进制数
%x格式化无符号十六进制数
%X格式化无符号十六进制数(大写)
%f格式化浮点数字,可指定小数点后的精度
%e用科学计数法格式化浮点数
%E作用同%e,用科学计数法格式化浮点数
%g根据值的大小决定使用%f或%e
%G作用同%g,根据值的大小决定使用%f或%E

【例子】

print('%c' % 97)  # a
print('%c %c %c' % (97, 98, 99))  # a b c
print('%d + %d = %d' % (4, 5, 9))  # 4 + 5 = 9
print("我叫 %s 今年 %d 岁!" % ('小明', 10))  # 我叫 小明 今年 10 岁!
print('%o' % 10)  # 12
print('%x' % 10)  # a
print('%X' % 10)  # A
print('%f' % 27.658)  # 27.658000
print('%e' % 27.658)  # 2.765800e+01
print('%E' % 27.658)  # 2.765800E+01
print('%g' % 27.658)  # 27.658
text = "I am %d years old." % 22
print("I said: %s." % text)  # I said: I am 22 years old..
print("I said: %r." % text)  # I said: 'I am 22 years old.'
  • 格式化操作符辅助指令
符号功能
m.nm 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)
-用作左对齐
+在正数前面显示加号( + )
#在八进制数前面显示零(‘0’),在十六进制前面显示’0x’或者’0X’(取决于用的是’x’还是’X’)
0显示的数字前面填充’0’而不是默认的空格

【例子】

print('%5.1f' % 27.658)  # ' 27.7'
print('%.2e' % 27.658)  # 2.77e+01
print('%10d' % 10)  # '        10'
print('%-10d' % 10)  # '10        '
print('%+d' % 10)  # +10
print('%#o' % 10)  # 0o12
print('%#x' % 108)  # 0x6c
print('%010d' % 5)  # 0000000005

练习题

1、字符串函数回顾

  • 怎么批量替换字符串中的元素?

    str.replace(old, new [, max])

  • 怎么把字符串按照空格进⾏拆分?

    str.split()

  • 怎么去除字符串⾸位的空格?

    str.lstrip()

2、实现isdigit函数

题目要求

实现函数isdigit, 判断字符串里是否只包含数字0~9

def test3(str1):
    for i in str1:
        if 48<ord(i) and ord(i)<57:     # 是一个数字
            continue
        else:                           # 不是数字
            return False
    return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tech沉思录

点赞加投币,感谢您的资瓷~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值