爱死你了 发表于 2015-11-30 11:34:05

Python学习(四)数据结构 —— list tuple range

序列类型 list   tuple   range
  

  list 和 tuple
  list:   列表,由 [] 标识; 有序;可改变列表元素
  tuple:  元组,由 () 标识; 有序;不可改变元组元素(和list的主要区别)
  list 和 tuple 的创建:



1 print([])                           # 空list
2 print(["a",1,True])                   # 元素类型不限
3 print()      # 列表推导式
4 print(list("a"),type(list("a")))      # 强制转化
5
6 print(())                           # 空tuple
7 print((1))                            # 不是tuple
8 print((1,))                           # 单一元素tuple 一定要加,
9 print(("a",1,True))                   # 元素类型不限
10 print(tuple("a"),type(tuple("a")))    # 强制转化
  空list l = []
  list 用一对方括号,用','隔开里面的元素l =    l = ["a",1,True]元素类型不限
  列表推导式,如: (下方会详细介绍 range 及 列表推导式)
  类型转换 list()
  
空tuplet = ()
  tuple 若只有一个元素时,注意表示为t = (1,)一定要有逗号
  tuple 用一对圆括号,用','隔开里面多个的元素t = ("a",1,True)元素类型不限
  类型转换 tuple()
  

  range
  range 可方便的生成一个等差的序列,有两种表示 range(stop) 、range(start, stop[, step]) ; 通常用在 for循环语句中
  range(stop) 表示 0 到 stop(不包含stop) 等差为1 的数,如 range(4) 表示 0 1 2 3
  range(start, stop[, step]) 表示 从 start 到 stop(不包含stop) 等差为step的数;step缺省为1,可设置为负数



1 print(type(range(4)))                   # range本身就是一个type
2 for i in range(4):
3   print(i)                            # 0 1 2 3
4 for i in range(-1):                     # 从0计数,无值
5   print(i)
6 for i in range(4,7):                  # 4 5 6
7   print(i)
8 for i in range(2,7,2):                  # 2 4 6
9   print(i)
10 for i in range(5,2,-1):               # 5 4 3
11   print(i)
  

  序列操作
  一般操作,不改变list本身

   

OperationResult



x in s
True if an item of s is equal to x, else False


x not in s
False if an item of s is equal to x, else True


s + t
the concatenation of s and t


s * n or n * s
n shallow copies of s concatenated


s
ith item of s, origin 0


s
slice of s from i to j


s
slice of s from i to j with step k


len(s)
length of s


min(s)
smallest item of s


max(s)
largest item of s


s.index(x[, i[, j]])
index of the first occurrence of x in s (at or after index i and before index j)


s.count(x)
total number of occurrences of x in s





1 s = ["a",1,True,["b"],2]      
2 print("a" in s)                # 判断元素存在于s
3 print("a" not in s)            # 判断元素不存在于s
4 print("b" in s)
5 print(1.0 in s)                # 这边不判断int float类型不同
6 print("1" in s)                # 这边的1为字符串
7 a =
8 b =
9 print(a+b)                     # 序列相加
10 print(a*3)                     # 序列乘法
11 s =
12 print(s,s,s)          # 通过下标来取出对应的元素
13 print(type(s))            
14 print(type(s))
15 print(s)                  # 取出一段list
16 print(s)                # 根据步长取出一段list
17 print(len(s))                  # list长度,即包含几个元素
18 sum = 0                        
19 for i in range(0,len(s)):      # 使用for循环来取出list的每个元素
20   print(s)
21   sum += i                   # 赋值的简单表达式,相当于 sum = sum + i
22 print(sum)                     # 总和
23 print(min(s),max(s))         # 取最小/最大;注意元素类型间若不可比较,会报错
24 s =
25 print(s.index(2))            # 查找对应元素第一次出现的下标
26 # print(s.index(4))            # 不存在该元素会报错
27 print(s.index(2,3))            # 从下标为3的开始找起
28 print(s.index(2,3,4))          # 从下标为3到下标4的阶段内找
29 print(s.count(2))            # 输出为2的元素的个数
30 print(s.count("2"))            # 找不到匹配元素,返回0
  上方列出的操作方法对 tuple 也都适用,因为并不改变序列本身的元素,如



1 s = (2,3,1,2,2,3)
2 print(s,s,len(s),s.count(2))            # 对tuple均适用   
  
  改变序列的操作:仅对 list 适用;若对 tuple 操作,会报错;clear() 和 copy() 是 Python 3.3 才新增的方法



OperationResult



s = x
item i of s is replaced by x


s = t
slice of s from i to j is replaced by the contents of the iterable t


s = t
the elements of s are replaced by those of t


del s
same as s = []


del s
removes the elements of s from the list


s.pop()
retrieves the item at i and also removes it from s


s.remove(x)
remove the first item from s where s == x


s.clear()
removes all items from s (same as del s[:])


s.append(x)
appends x to the end of the sequence (same as s = )


s.extend(t)
extends s with the contents of t (same as s = t)


s.insert(i, x)
inserts x into s at the index given by i (same as s = )


s.copy()
creates a shallow copy of s (same as s[:])


s.reverse()
reverses the items of s in place


  
  list的增、删、改的操作实际都比较实用,需要熟练掌握
  list元素更改
  可对 list 不同的下标表示法做以下操作,一般 list 下标的操作仅作对单一元素的更改赋值,如 s=1 ;对多个元素的操作见下方示例(仅供参考)





1 s =
2 s = "1"
3 print(s)                        # 对list的某一元素赋另外的值,类型也跟随改变
4 s = 1                        # 不可超过原list的长度,会报错
5 s =                 # 可对一段元素赋另外的值
6 print(s)      
7 s = ["x","x"]                # 可缺少,元素个数也就相应的减少了
8 print(s)      
9 s = ["x","x","x","x"]      # 可增加,元素个数也就相应的减加了
10 print(s)   
11 s =                   # 单个元素注意,相当于赋值,把序列赋予该元素
12 print(s)   
13 s =                
14 print(s)   
15 s =
16 s = ["x"]*4            
17 # s = ["x"]*3            # 这种表示方式元素个数一定需要相同,不然会报错
18 print(s)
list operation  list元素删除



1 s =
2 del s                        # 删除对应的元素   
3 print(s)   
4 s =
5 del s                      # 做删除
6 print(s)
7 s =
8 s.pop(3)
9 print(s.pop(3),s)               # 做删除,并且返回该元素的值
10 print(s.pop(),s)                  # 默认删除最后一个
11 s =
12 s.remove(1)                     # 删除第一个值为 1 的元素
13 print(s)                  
14 s.clear()                         # 置空,Python3.3引入
15 print(s)
  
  list元素增加



1 s =
2 s.append(5)                        # list 最后加一个元素
3 print(s)
4 s.extend()                  # list 最后拼接序列
5 print(s)
6 s.extend(range(3))
7 print(s)
8 s.insert(1,["x"])                  # 在1的位置插入["x"]
9 print(s)
  
  其他操作,reverse、copy 等



1 s =
2 c = s.copy()                  # 相当于 c = s
3 print(c)
4 c.reverse()
5 print(c)
6 s =
7 s.sort()                        # 排序
8 print(s)
9 # s = ["b",1,"a",True]          # 报错,必须是可比较的类型
10 s = ["b","a"]
11 s.sort()   
12 print(s)
  
页: [1]
查看完整版本: Python学习(四)数据结构 —— list tuple range