《看漫画学Python》6,7章

6.1序列

序列包括列表(list)、字符串(str)、元组(tuple)和字节序列(bytes)

6.1.1序列的索引操作

6.1.2加和乘操作

加(+)运算符可以将两个序列连接起来,乘(*)运算符可以将两个序列重复多次。

6.1.3切片操作

切片运算符的语法形式为[start:end:step]。其中,start是开始索引,end是结束索引,step是步长(切片时获取的元素的间隔,可以为正整数,也可以为负整数)。
切下的小切片包括start位置的元素,但不包括end位置的元素,start和end都可以省略。
步长为负值时,从右往左获取元素。

6.1.4成员测试

成员测试运算符有两个:in和not in,in用于测试是否包含某一个元素,not in用于测试是否不包含某一个元素。

a = 'hello'
print(a[0])
print(max(a))
print(min(a))
print(len(a))

h
o
e
5
a = 'Hello'
print('e' in a)
print('E' not in a)

True
True

6.2列表

列表是可变序列类型,可以追加,插入,删除,替换。

6.2.1创建列表

1.list(iterable)函数:参数iterable是可迭代对象(字符串、列表、元组、集合和字典等)。
2,[元素1,元素2]:指定具体的列表元素,列表元素以逗号分隔,需要使用中括号。

6.2.2追加元素

1.追加单个元素,用append(x)
2.在列表中追加多个元素时,可以使用加(+)运算符或列表的extend(t)方法。

6.2.3插入元素

想向列表中插入元素时,可以使用列表的list.insert(i,x)方法,其中,i指定索引位置,x是要插入的元素。

6.2.4替换元素

想替换列表中的元素时,将列表下标索引元素放在赋值符号(=)的左边,进行赋值即可。

6.2.5删除元素

使用列表的list.remove(x)方法,如果找到匹配的元素x,则删除该元素,如果找到多个匹配的元素,则只删除第一个匹配的元素。

list = [20,10,50,30]
list.append(80)
print(list)
list = [20,10,50,30]
t = [1,2,3]
list += t
print(list)
list = [20,10,50,30]
list.extend(t)
print(list)
[20, 10, 50, 30, 80]
[20, 10, 50, 30, 1, 2, 3]
[20, 10, 50, 30, 1, 2, 3]
list = [20,10,50,30]
list.insert(2,80) 
print(list)
list[1] = 80
print(list)
[20, 10, 80, 50, 30]
[20, 80, 80, 50, 30]
list = [20,10,50,30]
list.remove(10) 
print(list)
[20, 50, 30]

6.3元组

元组(tuple)是一种不可变序列类型。

6.3.1创建元组

1 tuple(iterable)函数:参数iterable是可迭代对象(字符串、列表、元组、集合和字典等)。
2 (元素1,元素2)小括号可省略。

6.2.3元组拆包

与元组打包相反的操作是拆包,就是将元组中的元素取出,分别赋值给不同的变量。

print(tuple('hello'))
t = 1,
print(t)
type(t)
t = (1,)
type(t)
a = ()
type(a)


('h', 'e', 'l', 'l', 'o')
(1,)





tuple
s_id,s_name = (102,'张三')
print(s_id)
print(s_name)

102
张三

6.4集合

集合(set)是一种可迭代的、无序的、不能包含重复元素的容器类型的数据。

6.4.1创建集合

1.set(iterable)函数:参数iterable是可迭代对象(字符串、列表、元组、集合和字典等)。
2.{元素1,元素2,元素3}

6.4.2修改集合

add(elem):添加元素,如果元素已经存在,则不能添加,不会抛出错误。
remove(elem):删除元素,如果元素不存在,则抛出错误。
clear( ):清除集合。

print(set('hello'))
print({20,10,20,50,30,10,30})
b = {}
print(type(b))
{'h', 'l', 'e', 'o'}
{10, 20, 50, 30}
<class 'dict'>
s_set = {'张三','李四','王五'}
s_set.add('董六')
print(s_set)
s_set.remove('李四')
print('李四' in s_set)
print(s_set)
s_set.clear()
print(s_set)
print()
{'董六', '张三', '王五', '李四'}
False
{'董六', '张三', '王五'}
set()

6.5字典

字典(dict)是可迭代的、通过键(key)来访问元素的可变的容器类型的数据。
字典由两部分视图构成:键视图和值视图。键视图不能包含重复的元素,值视图能。

6.5.1创建字典

1.dict()
2. {key1:value1,key2:value2,...,key_n:value_n}:指定具体的字典键值对,键值对之间以逗号分隔,最后用大括号括起来。

6.5.2修改字典

添加,替换,删除

6.5.3访问字典视图

items( ):返回字典的所有键值对视图。
keys( ):返回字典键视图。
values( ):返回字典值视图。

dict1 = {102:'张三',105:'李四',109:'王五'}
print(dict1[109])
dict1[110] = '董六'
print(dict1)
dict1[109] = '张三'
print(dict1)
print(dict1.pop(105))
print(dict1)
王五
{102: '张三', 105: '李四', 109: '王五', 110: '董六'}
{102: '张三', 105: '李四', 109: '张三', 110: '董六'}
李四
{102: '张三', 109: '张三', 110: '董六'}
dict1 = {102:'张三',105:'李四',109:'王五'}
print(dict1.items())
print(list(dict1.items()))
print(dict1.keys)
print(dict1.values())
print(list(dict1.values()))
dict_items([(102, '张三'), (105, '李四'), (109, '王五')])



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

TypeError                                 Traceback (most recent call last)

/var/folders/3m/vk7_y_ls1yl52kd_7wcpbz0h0000gn/T/ipykernel_16781/3310591198.py in <module>
      1 dict1 = {102:'张三',105:'李四',109:'王五'}
      2 print(dict1.items())
----> 3 print(list(dict1.items()))
      4 print(dict1.keys)
      5 print(dict1.values())


TypeError: 'list' object is not callable
print()
print()
print()
print()
print()

7.1字符串的表示方式

7.1.1普通字符串

7.1.2原始字符串

加r,则转义无用

7.1.3长字符串

对于长字符串,要使用三个单引号(''')或三个双引号(""")括起来。

s = 'hello \n world'
print (s)
s = 'hello \t world'
print (s)
s = 'hello \' world'
print (s)
s = 'hello \" world'
print (s)
s = 'hello \\ world'
print (s)
hello 
 world
hello 	 world
hello ' world
hello " world
hello \ world
s = '''
         早发白帝城
朝辞白帝彩云间,千里江陵一日还。 
两岸猿声啼不住,轻舟已过万重山。
'''
print (s)

         早发白帝城
朝辞白帝彩云间,千里江陵一日还。 
两岸猿声啼不住,轻舟已过万重山。

7.2 字符串与数字的相互转换

7.2.1字符串转换为数字

将字符串转换为数字,可以使用int( )和float( )实现,如果成功则返回数字,否则引发异常。
在默认情况下,int( )函数都将字符串参数当作十进制数字进行转换

7.2.2数字转换成字符串

将数字转换为字符串,可以使用str( )函数,str( )函数可以将很多类型的数据都转换为字符串。

print(int("80"))
print(int("80.0"))
print(float("80.0"))
print(int("AB"))
print(int("AB",16))
80



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

ValueError                                Traceback (most recent call last)

/var/folders/3m/vk7_y_ls1yl52kd_7wcpbz0h0000gn/T/ipykernel_16781/1220267228.py in <module>
      1 print(int("80"))
----> 2 print(int("80.0"))
      3 print(float("80.0"))
      4 print(int("AB"))
      5 print(int("AB",16))


ValueError: invalid literal for int() with base 10: '80.0'

7.3格式化字符串

要想将表达式的计算结果插入字符串中,则需要用到占位符。对于占位符,使用一对大括号({})表示。

7.3.1使用占位符

7.3.2格式化控制符

格式化控制符位于占位符索引或占位符名字的后面,之间用冒号分隔,语法:{参数序号:格式控制符}或{参数名:格式控制符}。

7.4操作字符串

7.4.1字符串查找

字符串的find( )方法用于查找子字符串。该方法的语法为str.find(sub[,start[,end]]),表示:在索引start到end之间查找子字符串sub,如果找到,则返回最左端位置的索引;如果没有找到,则返回-1。

7.4.2字符串替换

该方法的语法为str.replace(old,new[,count]),表示:用new子字符串替换old子字符串。count参数指定了替换old子字符串的个数,如果count被省略,则替换所有old子字符串。

7.4.3字符串分割

str.split(sep=None,maxsplit=-1),表示:使用sep子字符串分割字符串str。maxsplit是最大分割次数,如果maxsplit被省略,则表示不限制分割次数。

text = 'AB CD EF GH IJ'
print(text.replace(' ','|',2))
print(text.replace(' ','|'))
print(text.replace(' ','|',1))
print(text.replace(' ','|',6))
AB|CD|EF GH IJ
AB|CD|EF|GH|IJ
AB|CD EF GH IJ
AB|CD|EF|GH|IJ
text = 'AB CD EF GH IJ'
print(text.split(' '))
print(text.split(' ',maxsplit=0))
print(text.split(' ',maxsplit=1))
print(text.split(' ',maxsplit=2))
print()
print()
['AB', 'CD', 'EF', 'GH', 'IJ']
['AB CD EF GH IJ']
['AB', 'CD EF GH IJ']
['AB', 'CD', 'EF GH IJ']
# coding=ctf-8
# 一篇文章文本
wordstring = '''
it was the best of times it was the worst of times
it was the age of wisdom it was the age of the foolishness.
'''
# 将标点符号替换
wordstring = wordstring.replace('.','')

# 分割单词
wordlist = wordstring.split()

wordfreq = []
for w in wordstring:
    wordfreq.append(wordlist.count(w))

d = dict(zip(wordlist,wordfreq))
print(d)


{'it': 0, 'was': 0, 'the': 0, 'best': 0, 'of': 0, 'times': 0, 'worst': 0, 'age': 0, 'wisdom': 0, 'foolishness': 0}
posted @ 2021-10-31 20:57  20211301郑润芃  阅读(71)  评论(0编辑  收藏  举报