序列和元组

内置函数:
pow:幂运算
pow(x,y) --->x^y
abs:绝对值
abs(x) --->|x|
round:将浮点数圆整到最接近的整数,并且在两个整数一样近时圆整到偶数。
导入模块:import
模块math中包含的函数:
函数floor:---向下圆整
>>>import math
>>>math.floor(x)
math.floor(32.9) ---> 32
函数ceil:--->向上圆整
>>>math.ceil(x)
math.ceil(32.1) --->33
(特殊导入模块)若不从不同的模块导入多个同名函数,可使用:
from module import function
函数sqrt:---平方根
>>>from math inport sqrt
>>>sqrt(9) --->3
可以)用变量来引用函数:
>>>foo=math.sqrt
>>>foo(16) --->4
复数:模块cmath
>>>import cmath
>>>cmath.sqrt(-1) --->1j
注释:
#
''' '''
""" """
转义:
反斜杠(/)
拼接字符串:+
>>>"hello," + "world" --->hello,world
>>>x="hello"
>>>y='world'
>>>x+y --->hello,world
字符串:函数(类)str,函数repr
>>>"hello,\nworld"
hello,\nworld
>>>print("hello,\nworld")
hello
world
>>>print(str("hello,\nworld"))
hello
world
>>>print(repr("hello,\nworld"))
hello,\nworld
长字符串:要表示很长的字符串(跨多行的字符串),可使用三引号:
>>>print('''This is a very long string..............''')
常规字符串也可跨行:在行尾加反斜杠(\)
>>> 1+2+3+\
4
--->10
>>>print("the first line content is \
\"hello world!\"")
--->the first line content is "hello world!"
>>>print \
("hello,world!")
--->hello,world!
原始字符串:用前缀r表示:让字符串包含的每个字符都保持原样
>>> print("path=C:\\windows\\Program Files\\fnord\\file")
--->path=C:\windows\Program Files\fnord\file
>>> print(r'path=C:\windows\Program Files\fnord\\file')
--->path=C:\windows\Program Files\fnord\\file
注:原始字符串不能以单个反斜杠结尾。
>>> print(r"hello, \
world")
--->hello, \
world
##########**********##########
序列:列表和元组
序列是一种数据结构,序列中的每个元素都有编号,即位置或索引。
列表可以修改,元组不可以。
序列操作:索引,切片,相加,相乘,和成员资格检查,迭代
索引:获取元素
hello[1] --->e
sting="abcdefghij"
sting[1] --->b
sting[-1] --->j
months = ['January','February','March','April','May','June','July','Augest','Semtember','October','November','Decebmer']
endings=['st','nd','rd'] +17*['th'] + ['st','nd','rd'] + 7*['th'] + ['st']
year=input("Year: ")
month=input("month(1-12): ")
day=input("Day(1-31): "))
month_number=int(month)
day_number=int(day)
month_name=months[month_number-1]
day_name=day + endings[day_number-1]
print(month_name + " " + day_name + "," + yaer)
切片:可获取特定范围内的元素
使用两个索引,并用冒号:分隔
site[1:5] --->ttp:
注:用两个索引来指定切片的边界:其中第一个索引指定的元素包含在切片内,但第二个索引指定的元素不包含在切片内。
number=[1,2,3,4,5,6,7,8,9,10]
number[3:6] --->[4, 5, 6]
number[0:1] --->[1]
number[7:11] --->[8, 9, 10] (索引11指的是第12个元素,其并不存在,但确实到达了最后一个与元素)
number[:] --->[1,2,3,4,5,6,7,8,9,10] (复制整个序列)
number[-3:-1] --->[8, 9]
number[-3:] --->[8, 9, 10]
number[-3:0] --->[]
注:切片时,如果第一个索引指定的元素位于第二个索引指定的元素后面,结果就为空序列。
切片中的步长:
number=[1,2,3,4,5,6,7,8,9,10]
number[0:11:2] --->[1, 3, 5, 7, 9] (步长为2,每隔1个元素取1个元素)
number[1:11:2] --->[2, 4, 6, 8, 10]
number[::3] --->[1, 4, 7, 10] (步长为3,从序列中每隔2个元素取1个元素)
number[0:8:2] --->[1, 3, 5, 7]
number[11:0:-2] --->[10, 8, 6, 4, 2]
number[::-3] --->[10, 7, 4, 1]
number[0:11:-2] --->[]
number[5::-2] --->[6, 4, 2]
number[5::-2] --->[6, 4, 2]
number[:5:-2] --->[10, 8]
number[5::2] --->[6, 8, 10]
number[:5:2] ---[1, 3, 5]
步长为负数时,第一个索引必须必第二个索引大。
序列相加:
不能拼接不同类型的序列,如'列表' + '字符串'
>>>[1,2,3] + [4,5,6] --->[1,2,3,4,5,6]
>>>'hello,' + 'world' --->hello,world
乘法
将序列与数x相乘,表示重复该序列x次来创建一个新的序列
>>>3*'python' --->pythonpythonpython
>>>[2,4]*3 --->[2,4,2,4,2,4]
None,空列表和初始化
None表示什么都没有
空列表:用不包含任何内容的两个方括号[]表示
将列表的长度初始化为10:
sequence=[None]*10
content=input("input: ")
screen_width=80
text_width=len(content)
box_width=text_width + 6
left_margin=(screen_width - box_width) // 2
print()
print(" "*left_margin + "+" + "-"*(box_width-2) + "+")
print(" "*left_margin + "|" + " "*text_width + "|")
print(" "*left_margin + "|" + content + "|")
print(" "*left_margin + "|" + " "*text_width + "|")
print(" "*left_margin + "+" + "-"*(box_width-2) + "+")
成员资格检查
检查特定的值是否包含在序列中,使用布尔运算符in:检查是否满足指定的条件,并且返回相应的值(布尔值):满足是返回True,不满足时返回False
>>>permission="rw"
>>>"w" in permission --->True
>>>users=["mlh","foo","bar"]
>>>'mlh' in users ---> True
databasse=[['alert','123'],['dilbert','456'],['smith','789']]
username=input('username: ')
PIN=input("PIN code: ")
if [username,PIN) in database:
print('access granted')
else:
print("deny")
长度,最小值和最大值:
内置函数:len(*),min(*),max(*)
number=[1,3,5,7,9]
len(number) --->5
min(number) --->1
max(number) --->9
min(2,4,6,8) --->2
max(2,4,6,8) --->8
##########**********##########
列表
列表时可变的,即可以修改其内容
函数list:
可用字符串来创建列表,可将任何序列作为list的参数
>>>list("hello,world")
--->['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd']
将字符列表转换为字符串:
>>>a=['h', 'e', 'l', 'l', 'o', ',', 'w', 'o', 'r', 'l', 'd']
>>>''.join(a) --->hello,world
列表操作:
1、修改列表:给元素赋值
使用索引表示法给特定位置的元素赋值:(不能给不存在的元素赋值)
>>>x=[1,2,3,4,5]
>>>x[1]=9 --->x为[1,9,3,4,5]
2、删除元素:del
names=['alice','beth','cecil','dee','earl']
del names[2] --->names变为:['alice','beth','dee','earl']
>>> number=[1,2,3,4,5,6,7]
>>>del number[2:5] --->[1, 2, 6, 7]
3、给切片赋值:
>>>text=list("hello")
>>>text---> ['h', 'e', 'l', 'l', 'o']
>>>text[3:]=list['ys'] --->['h', 'e', 'l', 'y', 's']
>>>text[:]=[] --->[](text变为空)
插入新元素:
>>>number=[1,2,3,4,5]
>>>number[1:1]=[7,8,9,10] --->[1, 7, 8, 9, 10, 2, 3, 4, 5]
>>>number=[1,2,3,4,5,6,7]
>>>number[2:4]=[11,12,13,14,15] --->[1, 2, 11, 12, 13, 14, 15, 5, 6, 7]
>>>number=[1,2,3,4,5,6,7]
>>>number[1:4]=[] --->[1, 5, 6, 7]
注:顾前不顾后
列表方法:
1、append:将一个对象添加到列表末尾
number=[1,2,3,4,5]
number.append(9) --->number变为[1,2,3,4,5,9]
2、clear:清空列表的内容
number=[1,2,3,4,5]
number.clear() --->number为[]
3、copy:复制
常规复制只是将另一个名称关联列表:
>>>a=[1,2,3]
>>>b=a
>>>b[1]=4
>>>a --->[1,4,3]
>>>b --->[1,4,7]
要让a和b指向不同的列表,就必须让b关联到a的副本:
>>>a=[1,2,3]
>>>b=a.copy()
>>>b[1]=4
>>>a --->[1,2,3]
>>>b --->[1,4,7]
类似于使用:a[:]或list(a)
4、count:计算指定的元素在列表中出现的次数
>>>["to","be","or","not","to","be"].count('to')
--->2
>>>x=[[1,2],1,[2,1,[1,2,3]],1,]
>>>x.count(1) --->2
>>>x.count([1,2]) --->1
5、extend:可同时将多个值添加到列表末尾
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>a --->[1,2,3,4,5,6]
另:将列表赋给切片:
>>>a=[1,2,3]
>>>b=[4,5,6]
>>>a[len(a):]=b
>>>a --->[1,2,3,4,5,6]
6、index:在列表中查找指定的值第一次出现的索引
>>>knights=["we","are","the","knights","who","say","ni"]
>>>knights[4] --->who
>>>knights.index("who") --->4
7、insert:用于将一个对象插入列表
>>>number=[1,2,3,4,5,6,7,8]
>>>number.insert(3,"four")
>>>number --->[1,2,3,four,4,5,6,7,8]
另:使用切片赋值:
>>>number=[1,2,3,4,5,6,7,8]
>>>number[3:3]=["four"]
>>>number --->[1,2,3,four,4,5,6,7,8]
8、pop:从列表中删除一个元素(默认是删除最后一个元素),并且返回(被删除的)这一元素
>>>x=[1,2,3,4,5,6,7,8,9]
>>>x.pop() --->(返回一个值):9
>>>x --->[1,2,3,4,5,6,7,8]
>>>x=[1,2,3,4,5,6,7,8,9]
>>>x.pop(2) --->3
>>>x --->[1,2,4,5,6,7,8,9]
注:pop是唯一既修改列表又返回一个非None值的列表方法。
pop可实现一种常见的数据结构--栈:后进先出(LIFO)
push和pop是两种栈操作(加入和取走),push可用append来替代。
>>>x=[1,2,3]
>>>x.append(x.pop())
>>>x --->[1,2,3]
9、remove:用于删除第一个为指定的元素(指定的元素有多个时,只删除第一个)
>>>x=["to","be","or","not","to","be"]
>>>x.remove("be")
>>>x --->["to","or","not","to","be"]
>>>x.remove("bee") ---报错
注:remove是就地修改且不返回任何值。
10、reverse:按相反的顺序排列列表中的元素(会修改原来的列表)
>>>x=[1,2,3,4,5]
>>>x.reverse()
>>>x --->[5,4,3,2,1]
注:reverse是修改列表且不返回任何值。
函数reversed:
若要按相反的顺序迭代序列,可使用函数reversed:这个函数不返回列表,而是返回一个迭代器。可使用list将返回的对象的转换为列表:
>>>x=[1,2,3,4,5]
>>>list(reversed(x)) --->(返回结果)[5,4,3,2,1]
>>>x --->[1,2,3,4,5]
11、sort:对列表就地排序,使其元素按顺序排列,而不是返回排序后的列表的副本。
>>>x=[5,6,2,6,1,8]
>>>x.sort()
>>>x --->[1,2,5,6,6,8]
>>>x=[5,6,2,6,1,8]
>>>y=x.sort() ---这样写有问题
>>>print(y) --->None
>>>x --->[1,2,5,6,6,8]
>>>x=[5,6,2,6,1,8]
>>>y=x.copy()
>>>y.sort()
>>>y --->[1,2,5,6,6,8]
>>>x --->[5,6,2,6,1,8]
函数sorted:
>>>x=[5,6,2,6,1,8]
>>>y=sorted(x)
>>>y --->[1,2,5,6,6,8]
>>>x --->[5,6,2,6,1,8]
>>> x='python'
>>> y=sorted(x)
>>> y --->['h', 'n', 'o', 'p', 't', 'y']
12、高级排序:sort
rsort接受两个可选参数:key和reverse。这两个参数通常是按名称指定的,称为关键字参数。参数key:将其设置为一个用于排序的函数,一般不会直接使用这个函数来判断一个元素是否比另一个元素小,而是使用它来为每个元素创建一个键,再根据这些键对元素进行排序。
根据长度对元素进行排序:参数key设置为函数len
>>>x=["think","ok","throught","key","reverse"]
>>>x.sort(key=len)
>>>x --->['ok','key','think','reverse','throught']
另一关键字参数reverse:只需将其指定为一个真值(True或False),以指出是否需要按相反的顺序对列表进行排序。
>>>x=[5,6,2,6,1,8]
>>>x.sort(reverse=True)
>>>x --->[8,6,6,5,2,1]
>>>x=[5,6,2,6,1,8]
>>>x.sort(reverse=False)
>>>x --->[1,2,5,6,6,8]
函数sorted也可以接受参数key和reverse。
#########*********##########
元组:不可修改的序列
元组也是序列,用逗号分隔。
>>>1,2,3,4,5 --->返回结果:(1,2,3,4,5)
>>>(1,2,3,4,5) --->返回结果:(1,2,3,4,5)
>>>(1,) --->只有一个值时,逗号必须有
>>>() ---空元组
>>>3*(40+2) --->126
>>> 3*(40+2,) --->(42, 42, 42)
函数tuple:(与list类似)它将一个序列作为参数,并且将其转换为元组。如果参数已经是元组,则原封不动的返回它。
>>>tuple([1,2,3,4,5]) --->(1,2,3,4,5)
>>>tuple((1,2,3,4,5)) --->(1,2,3,4,5)
>>>tuple(['reverse']) --->('reverse',)
>>>tuple(('reverse')) --->('r','e','v','e','r','s','e')
>>>y="reverse"
>>>tuple(y) --->('r','e','v','e','r','s','e')
访问元组中的元素:
>>>x=1,2,3,4,5,6,7,8,9
>>>x[2] --->3
>>>x[2:6] --->(3,4,5,6)
元组的切片也是元组。
元组可用作映射中的键(以及集合的成员),而列表不行;
有些内置函数和方法返回元组。
posted @ 2018-08-06 21:08  Sky-wings  阅读(228)  评论(0编辑  收藏  举报