Python基础:序列

序列

  • 序列中每个元素都有一个跟位置相关的序号称为索引

  • 常见的序列:字符串、列表、元组

  • 序列对象可迭代,也就是可以遍历,序列对象的迭代要用到它的索引

  • 访问模式:元素从0开始通过下标偏移量进行访问

  • 一次可访问一个或多个元素,也叫做切片

  • 标准类型运算符:值比较、对象身份比较、布尔运算

  • 内建函数:序列类型转换内建函数、序列类型可用内建函数

  • list():把一个可迭代对象转换为列表

  • tuple([iterable]):把一个可迭代对象转换为元组

  • str(obj):把obj对象转换为字符串

  • len(sub):返回长度

  • max():返回序列或者参数集合中的最大值

  • min():返回序列或者参数集合中的最小值
    注意:使用max()和min()要保证数据类型是统一的

>>> a = 'i love Python!'
>>> a = list(a)
>>> a
['i', ' ', 'l', 'o', 'v', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', '!']
>>> b = (1,2,3,5,8,12,14,11)
>>> b = list(b)
>>> b
[1, 2, 3, 5, 8, 12, 14, 11]
>>> len(b)
8
>>> max(b)
14
>>> min(b)
1
  • zip():用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
>>> a = [1,2,3,4,5,6]
>>> b = [2,3,4,5,7,8]
>>> list(zip(a,b))
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 7), (6, 8)]

在这里插入图片描述

'apple' < 'banana'
Out[1]: True

[1,3,5] != [2,4,6]
Out[2]: True

aTuple = ('BA','The Boeing Company','122.64')
bTuple = aTuple
bTuple is not aTuple
Out[5]: False

('86.40' < '122.64' ) and ('apple' > 'banana')
Out[6]: False

  • 序列类型运算符:获取、重复、连接、判断
    在这里插入图片描述
week = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']

print(week[1],week[-2],'\n',week[1:4],'\n',week[:6],'\n',week[::-1])
Tuesday Saturday 
 ['Tuesday', 'Wednesday', 'Thursday'] 
 ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] 
 ['Sunday', 'Saturday', 'Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday']

'apple' * 3
Out[9]: 'appleappleapple'

'pine' + 'apple'
Out[10]: 'pineapple'

'BA' in ('BA','The Boeing Company','122.64')
Out[11]: True

week[-5::]
Out[12]: ['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

week[1:-1]
Out[13]: ['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  • 序列类型转换内建函数
    在这里插入图片描述
>>> Str = 'hello,world!'
>>> len(Str)
12#长度
>>> sorted(Str)
['!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
#排序
>>> max(Str)
'w'
#最大
>>> min(Str)
'!'
#最小
>>> Str = ('h','e','l','l','o')
>>> print(list(reversed(Str)))
['o', 'l', 'l', 'e', 'h']
>>> Str = 'hello world'
>>> print(list(reversed(Str)))
['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'h']
#reversed()函数:反转
>>> sum([1,2,3,4,5,6,7,8,9])
45
#求和
>>> list('hello,world!')
['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd', '!']
>>> tuple('hello world!')
('h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!')
  • enumerate()函数:既遍历索引又遍历值时使用较为方便
dict = [{"name":"小明","age":19},{"name":"小王","age":"20"},{"name":"小李","age":"21"}]
for index,t in enumerate(dict):
    print(index,t)
    
0 {'name': '小明', 'age': 19}
1 {'name': '小王', 'age': '20'}
2 {'name': '小李', 'age': '21'}
  • zip()函数:由一系列可迭代的对象作为参数,返回一个zip对象,把对象对应的元素打包成一个一个的元组
x = [1,2,3,4,5,6]
y = ['a','b','c','d','e','f']
for num,str in zip(x,y):
    print(num,str)
1 a
2 b
3 c
4 d
5 e
6 f

字符串

  • 常用方法:
    在这里插入图片描述

  • casefold:把整个字符串的所有字母改成小写

  • center(width):将字符串居中,并使用空格填充至长度width的新字符串。

  • count(sub[,start[,end]]):返回sub在字符串里面出现的次数,start和end参数表示范围,可选。

  • endswith(sub[,start[,end]]):检查字符串是否以sub子字符串结束,如果是返回True,如果不是返回False,start和end表示范围,可选。

  • find(sub[,start[,end]]):检测sub是否包含在字符串中,如果有则返回索引值,否则返回-1,start和end表示参数范围,可选。

  • index(sub[,start[,end]]):跟find方法一样,不过如果sub不在字符串中会产生一个异常。

  • isalnum():如果字符串至少有一个字符并且所有字符都是字母或数字返回True,否则返回False.

  • isalpha():如果字符串中至少含有一个字符并且所有字符都是字母返回True,否则返回False.

  • isdecimal():如果字符串中只包含十进制数字则返回True,否则返回False.

  • isdigit():如果字符串中只包含数字则返回True,否则返回False.

  • islower():如果字符串中至少包含一个区分大小写的字符,并且这些字符都是小写则返回True,否则返回False。

  • isnumeric():如果字符串中只包含数字字符,则返回True,否则返回False.

  • isspace():如果字符串中只包含空格,则返回True,否则返回False.

  • istitle():如果字符串是标题化(所有的单词都是以大写开始其余字母均是小写)则返回True,否则返回False.

  • isupper():如果字符串中至少包含一个区分大小写的字符,并且这些字符都是大写则返回True,否则返回False.

  • join(sub):以字符串作为分隔符,插入到sub中所有的字符之间。

>>> aStr = 'HELLO,python'
>>> aStr.casefold()
'hello,python'
>>> aStr.center(20)
'    HELLO,python    '
>>> a = 'absabdabsdbaasd'
>>> a.count('a')
5
>>> a.count('a',1,10)
2
aStr = 'hello,world!'#字符串
bStr = "student"
cStr = '''the boeing'''
>>> s1 = "I'm a student"
>>> s1
"I'm a student"
>>> s2 = '''hello
world'''
>>> s2
'hello\nworld'
>>> s3 = r'd:\Python\test.py'

aStr = "Hello,world!"
bStr = aStr[:6] + "Python!"
count = 0
for ch in bStr[:]:
    if ch in ',.!?':
        count += 1
print("Punctuation marks = {:d}".format(count))
print(bStr)
Punctuation marks = 2
Hello,Python!
>>> s1 = "I'm a student"
>>> s1
"I'm a student"
>>> s2 = '''hello
world'''
>>> s2
'hello\nworld'
>>> s3 = r'd:\Python\test.py'
>>> song = "Blowing in the wind"
>>> song.find("the")
11
>>> song.find("the",8,12)
-1
>>> song.lower()#不改变本身的song
'blowing in the wind'
>>> song
'Blowing in the wind'
>>> song.split(' ')#分割
['Blowing', 'in', 'the', 'wind']
>>> song.replace("the","that")
'Blowing in that wind'
>>> aList = ["hello","world"]
>>> ' '.join(aList)
'hello world'
>>> y = "你好"
>>> z = y.encode('utf-8')#编码
>>> z
b'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> t = z.decode()#解码
>>> t
'你好'
>>> c = b'\xe6\x89\x8e\xe5\xbf\x83\xe4\xba\x86\xef\xbc\x8c\xe8\x80\x81\xe9\x93\x81'
>>> t = c.decode()
>>> t
'扎心了,老铁'
aStr = 'What do you think of this saying "NO pain,NO gain"?'
tempStr = aStr.split("\"")[1]
if tempStr.istitle():
    print('It is title format.')
else:
    print('It is not title format.')
print(tempStr.title())
It is not title format.
No Pain,No Gain

在这里插入图片描述

  • 回文方法:
str = str[::-1]

在这里插入图片描述

列表

  • 列表是可扩展的容器对象
  • append()
  • copy()
  • count()
  • extend()
  • index()
  • insert()
  • pop()
  • remove()
  • reverse()
  • sort()
  • 注意sort()与sorted(),reverse()与reversed()
aList = [2,3,6,7,11]#列表
pList = [('AXP','American Express Company','78.51'),('BA','The Boeing Company','184.76')]#由元组组成的列表
jScores = [9,9,8.5,10,7,8,8,9,8,10]
aScore = 9
jScores.sort()
jScores.pop()#弹出最后一个值
jScores.pop(0)#加上索引弹值
jScores.append(aScore)
aveScore = sum(jScores)/len(jScores)
print(jScores)
print(aveScore)
[8, 8, 8.5, 9, 9, 9, 10, 9]
8.722222222222221

week = ['Monday','Tuesday','Wednesday','Thursday','Friday']
weekend = ['Saturday','Sunday']
week.extend(weekend)
for i,j in enumerate(week):
    print(i+1,j)
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday
  • 参数的作用:list.sort(key = None,reverse = False)
numList = [3,11,5,8,16,1]
fruitList = ['apple','banana','pear','lemon','avocado']
numList.sort(reverse = True)
print(numList)
fruitList.sort(key = len)
print(fruitList)
[16, 11, 8, 5, 3, 1]
['pear', 'apple', 'lemon', 'banana', 'avocado']
  • 列表解析:在改变列表时使用
[expression for expr in sequence 1
			for expr2 in sequence 2
			for exprN in sequence N
			if condition]
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> [x ** 2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x ** 2 for x in range(10) if x ** 2 < 50]
[0, 1, 4, 9, 16, 25, 36, 49]
>>> [(x + 1,y + 1) for x in range(2) for y in range(2)]
[(1, 1), (1, 2), (2, 1), (2, 2)]
def clean_list(lst):
    cleaned_list = []
    for item in lst:
        for c in item:
            if c.isalpha() != True:
                item = item.replace(c,'')
        cleaned_list.append(item)
    return  cleaned_list
coffee_list = ['32Latte','_Americano30','/34Cappuccino','Mocha35']
cleaned_list = clean_list(coffee_list)
1 Latte
2 Americano
3 Cappuccino
4 Mocha

元组

aTuple = ('Sunday','happy')#元组
pList = [('AXP','American Express Company','78.51'),('BA','The Boeing Company','184.76')]#由元组组成的列表
>>> bTuple = (['Monday',1],2,3)
>>> bTuple
(['Monday', 1], 2, 3)
>>> bTuple[0][1]
1#获得二级长度值
>>> len(bTuple)
3
>>> bTuple[1:]
(2, 3)#切片
>>> 2020,
(2020,)#创建一个元素的元组
>>> aList = ['AXP','BA','CAT']
>>> aTuple = ('AXP','BA','CAT')
>>> aList[1] = 'Alibiabia'
>>> print(aList)
['AXP', 'Alibiabia', 'CAT']#列表可以改变元组不可以改变
>>> aList = [3,5,2,4]
>>> aList
[3, 5, 2, 4]
>>> sorted(aList)
[2, 3, 4, 5]
>>> aList
[3, 5, 2, 4]#sorted()生成一个副本不改变原始列表
>>> aList.sort()
>>> aList
[2, 3, 4, 5]#原始列表被改变
>>> bTuple = (2,3,4,7,5,6)
>>> bTuple
(2, 3, 4, 7, 5, 6)
>>> sorted(bTuple)
[2, 3, 4, 5, 6, 7]
>>> bTuple.sort()#元组对象没有sort方法
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    bTuple.sort()
AttributeError: 'tuple' object has no attribute 'sort'

元组在Python中的使用:

  • 在映射中作为键来使用,利用元组不可变性
  • 作为函数的特殊类型参数
>>> foo('Hello,')
Hello, world!
>>> foo('Hello,',args2='Python!')
Hello, Python!
>>> foo(args2='Apple!',args1='Hello,')
Hello, Apple!
>>> foo('Hello,','wangdachui','niuyun','linling')
Hello,
('wangdachui', 'niuyun', 'linling')#Python中利用元组作为函数的参数,元组的长度是不定长的(*号可以用来收集参数)
  • 作为函数的特殊返回类型
>>> def foo():
	return 1,2,3

>>> foo()
(1, 2, 3)#
发布了73 篇原创文章 · 获赞 2 · 访问量 3161

猜你喜欢

转载自blog.csdn.net/soulmate______/article/details/104983534
今日推荐