序列的运算、操作、函数/方法

1.序列

(1) 序列的标准类型运算

a) <、>、<=、>=、==、!= 值比较

例如:

>>>'apple' < 'banana'
True
>>>[1,3,5] != [2,4,6]
True
b) is、is not 对象身份比较
>>>aTuple=('BA','The Boeing Company','122.64')
>>>bTuple=aTuple
>>>bTuple is not aTuple
False
c) and、or、not 逻辑运算

例如:

>>>('86.40' < '122.64') and ('apple' > 'banana')
False

(2) 通用序列类型操作

a) seq[start: end] 切片操作

例如:

>>> week = ['Monday','Tuesday','Wendesday','Thursday','Friday','Saturday','Sunday']
>>> print(week[1],week[-2],'\n',week[1:4],'\n',week[:6],'\n',week[::-1])
Tuesday Saturday
 ['Tuesday', 'Wendesday', 'Thursday']
 ['Monday', 'Tuesday', 'Wendesday', 'Thursday', 'Friday', 'Saturday']
 ['Sunday', 'Saturday', 'Friday', 'Thursday', 'Wendesday', 'Tuesday', 'Monday']
b) * 重复组合序列数据

例如:

>>> 'apple'*3
'appleappleapple'
>>> ['apple']*3
['apple', 'apple', 'apple']
c) + 连接2个序列

例如:

>>> 'pine'+'apple'
'pineapple'
>>> ['apple','orange']+['grape']
['apple', 'orange', 'grape']
d) in、not in 判断元素是否存在序列中

例如:

>>> 'BA' in ('BA' ,'The Beoing Company','122.64')
True

(3) 序列常用函数

a) 序列类型转换内建函数:

list(iter) 将可迭代对象iter转换成列表

tuple(iter) 将可迭代对象iter转换成元组

str(obj) 将对象obj转换成字符串表示

>>> 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')
>>> str(['apple','banana'])
"['apple', 'banana']"
b) 其它常用内建函数:

len(sequence) 返回sequence的长度,为整型类型

sorted(iter, key, reverse) 返回可迭代对象iter排序后的列表,key用来指定排序的规则,reverse用来指定顺序还是逆序排列

reversed(sequence) 返回序列sequence逆序排列后的迭代器

sum(iter, start) 将iter中的数值和start参数的值相加,返回float类型数值

max(iter) 返回可迭代对象iter中的最大值

min(iter) 返回可迭代对象iter中的最小值

enumerate(iter[, start]) 返回一个enumerate对象,可生成一个迭代器,该迭代器的元素是由参数iter元素的索引和值组成的元组

zip(iter1 [,iter2 […]]) 返回一个zip对象,可生成一个迭代器,该迭代器的第n个元素是每个可迭代对象的第n个元素组成的元组

2.字符串

字符串常用方法:

方法 描述

s.capitalize() 返回字符串s首字母大写其余小写的形式|

s.lower() 返回字符串s的小写形式

s.upper() 返回字符串s的大写形式

s.title() 返回字符串s的标题形式即单词首字母大写形式

s.format(*args, **kwargs) 格式化字符串操作

s.count(sub[, start[, end]]) 返回指定字符在[指定位置的]字符串s中出现的次数

s.find(sub[, start[, end]]) 返回指定字符在[指定位置的]字符串s中出现的索引号,找不到则返回-1

s.index(sub[, start[, end]]) 与 find()类似,不同的是如果找不到会引发ValueError异常

s.replace(old, new[, count]) 把字符串s中的old(旧字符串)替换成new(新字符串)。如果指定第三个参数count,则仅仅替换前count次出现的子串

s.lstrip([chars]) 移除字符串s左边的指定字符(默认为空格),返回移除字符串s左边指定字符后生成的新字符串

s.rstrip([chars]) 移除字符串s末尾的指定字符(默认为空格),返回移除字符串s末尾指定字符后生成的新字符串

s.strip([chars]) 移除字符串s头尾指定的字符(默认为空格),返回移除字符串s头尾指定字符后生成的新字符串

s.join(iterable) 用指定的字符串s连接元素为字符串的可迭代对象

s.split(sep=None, maxsplit=-1) 以指定的字符作为分隔符(默认为空格)分割字符串s,maxsplit指分割次数(默认为不限制次数)

s.endswith(suffix[, start[, end]]) 判断字符串s[的指定位置]是否以后缀suffix结尾

s.startswith(prefix[, start[, end]]) 判断字符串s[的指定位置]是否以前缀prefix开头

eg:

>>> song = "Blowing in the wind"
>>> song.find("the")
11
>>> song.find("the",8,12)
-1
>>> song.lower()
'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
'你好'

eg:字符串中标点符号的个数:

>>> aStr = "Hello,World!"
>>> bStr = aStr[:6]+"python!"
>>> bStr
'Hello,python!'
>>> count = 0
>>> for ch in bStr[:]:
...     if ch in ',.!?':
...         count += 1
...
>>> print('There are {0:d} punctuation marks.'.format(count))
There are 2 punctuation marks.

eg:判断是否为回文字符串

>>> sStr = 'acdhdca'
>>> if(sStr == ''.join(reversed(sStr))):
...     print('yes')
... else:
...     print('no')
...
yes

eg:判断是否为标题格式

>>> aStr = 'What do you think of this saying "No pain,No gain"?'
>>> lindex = aStr.index('\"',0,len(aStr))
>>> rindex = aStr.rindex('\"',0,len(aStr))
>>> tempStr = aStr[lindex+1:rindex]
>>> tempStr
'No pain,No gain'
>>> if tempStr.istitle():
...     print('yes')
... else:
...     print('no')
...
no
>>> print(tempStr.title())
No Pain,No Gain

3.列表

列表是可扩展的容器对象,可以包含不同类型的对象。

eg:动态创建列表

>>> [x**2 for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [(x+1,y+1) for x in range(2) for y in range(2)]
[(1, 1), (1, 2), (2, 1), (2, 2)]

列表常用方法

方法 描述

l.append(obj) 在列表l末尾添加新的对象

l.count(obj) 统计某个元素在列表l中出现的次数

l.extend(seq) 在列表l末尾一次性追加另一个序列seq中的多个值(用新列表扩展原来的列表)

l.index(obj) 从列表l中找出某个值第一个匹配项的索引位置,索引从0开始

l.insert(index, obj) 将对象obj插入列表l中索引为index的元素前

l.pop(index) 移除列表l中索引为index的一个元素(默认为最后一个元素),并且返回该元素的值

l.remove(obj) 移除列表l中某个值的第一个匹配项

l.reverse() 将列表l中的元素反转

l.sort(key=None, reverse=False) 对原列表l进行排序,可通过参数key指定排序依据,通过参数reverse指定顺序(默认方式)或逆序排列

eg:sorted()函数与列表的sort()方法的区别

利用sorted()函数对列表进行排序,只是新生成了一个列表的副本,原始列表内容没有改变。通过列表的sort()方法对列表进行排序,是对原始列表真正的排序,列表内容会改变。

>>> aList=[3,5,2,4]
>>> aList
[3, 5, 2, 4]
>>> sorted(aList)
[2, 3, 4, 5]
>>> aList
[3, 5, 2, 4]
>>> aList.sort()
>>> aList
[2, 3, 4, 5]

4.元组

元祖和列表的区别:除了列表用[]表示、元组用()表示之外,最重要的区别是,列表元素可以改变,元组元素不可以改变

eg:创建元组

>>> bTuple = (['Monday',1],2,3)
>>> bTuple[0][1]
1
>>> len(bTuple)
3
>>> bTuple[1:]
(2, 3)
>>> 2014,
(2014,)

元组用在什么地方?

(1)在映射类型中当做键使用

(2)函数的特殊类型参数

eg: 可变长位置参数:

>>> def foo(args1,*argst):
...     print(args1)
...     print(argst)
...
>>> foo('Hello','Wangdachui','Niuyun','Linling')
Hello
('Wangdachui', 'Niuyun', 'Linling')

(3)作为函数的特殊返回值

>>> def foo():
...     return 1,2,3
...
>>> foo()
(1, 2, 3)

元组常用函数:

函数 描述

len(t) 计算元组t的元素个数

max(t) 返回元组t中元素的最大值

min(t) 返回元组t中元素的最小值

tuple(seq) 将序列seq转换为元组

参考文献

[1]https://www.coursera.org/learn/hipython/home/week/2

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值