Python之路,第六篇:Python入门与基础6

 

python 列表

           序列类型简介(sequence)

                          字符串str
                         列表list
                         元祖tuple

           概念:

                     列表是由一系列特定元素组成的,元素之间可能没有任何关联,但是他们之间有先后顺序关系
                     列表可以改变各个元素的值
                     列表是一个容器。

           空列表: L = [ ]  # 空列表

                          L = list()  # 空列表,是一个函数

           创建一个非空列表:

                         L = [1,2,3,4,5]

           列表的生成函数list():

                        list()生成一个空列表等同于[ ]  ;

                        list(iterable)     用一个可迭代对象初始化列表

                       例子:

1 >>> l=list(range(11))
2 >>> l
3 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4 >>> 
5 >>> s='abcdefg'
6 >>> l=list(s)
7 >>> l
8 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
9 >>> 
list1

          列表的运算符

                    +     、 +=    、  *  、 *=

                 说明: + 号运算符用于拼接列表;  += 运算符用于原来列表与右侧列表拼接生成的新列表(x = x+y 等同于 x +=y)

                           * 号运算符用于生成重复的列表 ;   * =号运算符用于原列表生成重复的列表,并改变变量的绑定;

 1 >>> x=[1,2,3]
 2 >>> y=[4,5,6]
 3 >>> z = x + y
 4 >>> z
 5 [1, 2, 3, 4, 5, 6]
 6 >>> len(z)
 7 6
 8 >>> m = y + x  
 9 >>> m
10 [4, 5, 6, 1, 2, 3]  
11 >>> len(m)
12 6
13 >>> 
+号拼接
1 >>> x=[1,2,3]
2 >>> y=[4,5,6]
3 >>> x += y
4 >>> x
5 [1, 2, 3, 4, 5, 6]
6 >>> y
7 [4, 5, 6]
8 >>> 
+=号拼接
1 >>> [1,2] * 3
2 [1, 2, 1, 2, 1, 2]
3 >>> 3 * [1,2]
4 [1, 2, 1, 2, 1, 2]
5 >>> 
*
1 >>> x = [1,2,3]
2 >>> x *= 4
3 >>> x
4 [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
5 >>> 
*=

          列表的关系(比较)运算符:

                 >     >=    <     <=    ==    !=

 1 >>> x = [1,2,3]
 2 >>> y = [2,3,4]
 3 >>> x != y
 4 True
 5 >>> x > y
 6 False
 7 >>> x < y
 8 True
 9 >>> x == y
10 False
11 >>> [1,2,3] == [3,2,1]
12 False
13 >>> [1,'two'] < ['two',1]
14 Traceback (most recent call last):
15   File "<pyshell#59>", line 1, in <module>
16     [1,'two'] < ['two',1]
17 TypeError: unorderable types: int() < str()
18 >>>#字符串和列表是不能比较的
View Code

           列表的 in   /  not in 运算符

 1 >>> x = [1,'two', 3.0, "four"]
 2 >>> 1 in x
 3 True
 4 >>> 2 not in x
 5 True
 6 >>> "3" in x
 7 False
 8 >>> 10 in x
 9 False
10 >>> 
in、not in

 

          列表的基本操作

                   索引(indes): 列表[ 索引 ] ,等同于字符串索引;正向索引(0  , len(x)-1 ),反向索引(- len(x) ,-1),

 1 >>> x
 2 [1, 'two', 3.0, 'four']
 3 >>> x[0]
 4 1
 5 >>> x[1]
 6 'two'
 7 >>> x[2]
 8 3.0
 9 >>> x[4]
10 Traceback (most recent call last):
11   File "<pyshell#11>", line 1, in <module>
12     x[4]
13 IndexError: list index out of range
14 >>> 
View Code

 

          列表是可变的,可以通过赋值改变列表的元素;

1 >>> x = [1,2,3,4]
2 >>> x[2]=3.14
3 >>> x
4 [1, 2, 3.14, 4]
5 >>> 
可变的list

 

           切片slice      [ : ]   [ : : ]

                  列表的切片规则等同于字符串的切片规则; 

 1 >>> x
 2 [1, 2, 3.14, 4]
 3 >>> x[1:2]
 4 [2]
 5 >>> x[:]
 6 [1, 2, 3.14, 4]
 7 >>> x[::]
 8 [1, 2, 3.14, 4]
 9 >>> x[::2]
10 [1, 3.14]
11 >>> 
slice,步长

 

           切片赋值:

                  作用:可以改变原列表的排列,及插入删除数据,列表中可以用切片改变列表对应的元素的值;

 1 >>> x
 2 [1, 2, 3.14, 4]
 3 >>> x[0:1]
 4 [1]
 5 >>> x[0:1]=[1.1,2.2]
 6 >>> x
 7 [1.1, 2.2, 2, 3.14, 4]
 8 >>> x[1:1] #空值
 9 []
10 >>> x[1:1]=[3.3,4.4]
11 >>> x
12 [1.1, 3.3, 4.4, 2.2, 2, 3.14, 4]
13 >>> 
切片赋值

 

                 注意事项:对于步长大于1 的切片可能会出现赋值错误;

                                   切片赋值是改变原列表,不会生成新列表;

 1 >>> x
 2 [1.1, 3.3, 4.4, 2.2, 2, 3.14, 4]
 3 >>> x[0::2]
 4 [1.1, 4.4, 2, 4]
 5 >>> x[0::2]=[11,12]   #赋值的数量不够4个
 6 Traceback (most recent call last):
 7   File "<pyshell#27>", line 1, in <module>
 8     x[0::2]=[11,12]
 9 ValueError: attempt to assign sequence of size 2 to extended slice of size 4
10 >>> x[0::2]=[11,22,33,44]
11 >>> x
12 [11, 3.3, 22, 2.2, 33, 3.14, 44]
13 >>> 
切片

 

            python3中常用的序列函数:

                  len(x)   返回序列的长度

                  max(x) 返回序列最大值的元素

                  min(x) 返回序列最小值的元素

                 sum(x) 返回序列中所有元素的总和;  

                 any(x)  真值测试,如果列表其中一个值为真值,则返回True

                 all(x)    真值测试,如果列表所有值都为真值,则返回True

序列函数

                练习:求列表的最大值,最小值,平均值

 1 #!/usr/bin/python
 2 
 3 n1 = int(input("请输入第一个整数:"))
 4 n2 = int(input("请输入第二个整数:"))
 5 n3 = int(input("请输入第三个整数:"))
 6 list1=[n1,n2,n3]
 7 print("列表:",list1)
 8 print("列表的最大值是:",max(list1))
 9 print("列表的最小值是:",min(list1))
10 n = len(list1)
11 print("列表的平均值是:",sum(list1)//n)
12 >>> ================================ RESTART ================================
13 >>> 
14 请输入第一个整数:20
15 请输入第二个整数:30
16 请输入第三个整数:40
17 列表: [20, 30, 40]
18 列表的最大值是: 40
19 列表的最小值是: 20
20 列表的平均值是: 30
21 >>> 
list1 
list2
 1 #!/usr/bin/python
 2 
 3 n1 = int(input("请输入第一个整数:"))
 4 n2 = int(input("请输入第二个整数:"))
 5 n3 = int(input("请输入第三个整数:"))
 6 #list1=[n1,n2,n3]
 7 list1 = []
 8 list1[0:0]=[n1]
 9 list1[0:0]=[n2]
10 list1[0:0]=[n3]
11 print("列表:",list1)
12 print("列表的最大值是:",max(list1))
13 print("列表的最小值是:",min(list1))
14 n = len(list1)
15 print("列表的平均值是:",sum(list1)//n)
16 >>> ================================ RESTART ================================
17 >>> 
18 请输入第一个整数:20
19 请输入第二个整数:30
20 请输入第三个整数:40
21 列表: [40, 30, 20]
22 列表的最大值是: 40
23 列表的最小值是: 20
24 列表的平均值是: 30
25 >>> 

 

              python3中常用的列表方法:

                     见help(lsit)

L.index(v,[,begin[,end]] )             #返回对应元素的索引下标,begin为开始索引,end为结束索引
L.insert(index,obj)                       #将某个元素插放到列表中指定的位置
L.count(x)                                    # 返回列表中元素的个数
L.remove(x)                                #从列表中删除第一次出现在列表中的值
L.copy()                                     #复制此列表(只复制一层,不进行深层复制)
L.append(x)                               #在列表的尾部添加单个元素
L.extend(list)                             #向列表追加另一个列表
L.clear()                                    #清空列表,等同于L[:] = []
L.sort(reverse=False)               #将列表的顺序按值的小到大顺序进行排列(升序);reverse=True 降序;
L.reverse()                               #列表反转(头变尾,尾变头)
L.pop([index])                           #删除索引对应的元素,如果不加索引,默认删除最后元素,同时返回移除元素 

  1 >>> 
  2 >>> l=[1,2,3,4,5,6,7,8]
  3 >>> l.index(2)
  4 1
  5 >>> l.index(4)
  6 3
  7 >>> l.index(3,5)
  8 Traceback (most recent call last):
  9   File "<pyshell#50>", line 1, in <module>
 10     l.index(3,5)
 11 ValueError: 3 is not in list
 12 >>> l.index(3,1)
 13 2
 14 >>> l.index(6, 3, 8)
 15 5
 16 >>> l
 17 [1, 2, 3, 4, 5, 6, 7, 8]
 18 >>> l.insert(3,10)
 19 >>> l
 20 [1, 2, 3, 10, 4, 5, 6, 7, 8]
 21 >>> l.count(5)
 22 1
 23 >>> l.remove(4)
 24 >>> l
 25 [1, 2, 3, 10, 5, 6, 7, 8]
 26 >>> l.remove(11)
 27 Traceback (most recent call last):
 28   File "<pyshell#59>", line 1, in <module>
 29     l.remove(11)
 30 ValueError: list.remove(x): x not in list
 31 >>> l.append(11)
 32 >>> l
 33 [1, 2, 3, 10, 5, 6, 7, 8, 11]
 34 >>> l.extend([12,13,14,15])
 35 >>> l
 36 [1, 2, 3, 10, 5, 6, 7, 8, 11, 12, 13, 14, 15]
 37 >>> l.clear(0
 38     
 39 KeyboardInterrupt
 40 >>> l.clear()   #clear方法清空
 41 >>> l
 42 []
 43 >>> l = [1,2,3,4,5]
 44 >>> l[:] = []
 45 >>> l
 46 []
 47 >>> l = [1,2,3,4,5]
 48 >>> l
 49 [1, 2, 3, 4, 5]
 50 >>> l2 = l
 51 >>> l
 52 [1, 2, 3, 4, 5]
 53 >>> l2
 54 [1, 2, 3, 4, 5]
 55 >>> l[:] = []   #切片清空
 56 >>> l
 57 []
 58 >>> l2
 59 []
 60 >>> l = [1,2,3,4,5]
 61 >>> l2 = l
 62 >>> l2
 63 [1, 2, 3, 4, 5]
 64 >>> l = []
 65 >>> l
 66 []
 67 >>> l2
 68 [1, 2, 3, 4, 5]
 69 >>> l = [5,7,3,8,4,1,10]
 70 >>> l.sort()
 71 >>> l
 72 [1, 3, 4, 5, 7, 8, 10]
 73 >>> l.sort(reverse=True)
 74 >>> l
 75 [10, 8, 7, 5, 4, 3, 1]
 76 >>> l
 77 [10, 8, 7, 5, 4, 3, 1]
 78 >>> l = [ 2,7,1,5,8]
 79 >>> l.reverse()
 80 >>> l
 81 [8, 5, 1, 7, 2]
 82 >>> l.reverse()
 83 >>> l
 84 [2, 7, 1, 5, 8]
 85 >>> l.pop()
 86 8
 87 >>> l
 88 [2, 7, 1, 5]
 89 >>> l.pop([2])
 90 Traceback (most recent call last):
 91   File "<pyshell#97>", line 1, in <module>
 92     l.pop([2])
 93 TypeError: 'list' object cannot be interpreted as an integer
 94 >>> l.pop(2)
 95 1
 96 >>> l
 97 [2, 7, 5]
 98 >>> l2 = l
 99 >>> l2
100 [2, 7, 5]
101 >>> l2 = l.copy()
102 >>> l2
103 [2, 7, 5]
104 >>> id(l2)
105 57182664
106 >>> id(l)
107 57183112
108 >>> l2 = l
109 >>> l2
110 [2, 7, 5]
111 >>> id(l)
112 57183112
113 >>> id(l2)
114 57183112
115 >>> 
list方法

            嵌套列表

 1 >>> L = [20,21,22]
 2 >>> L1 = [10,L,30]
 3 >>> L1
 4 [10, [20, 21, 22], 30]
 5 >>> L2 = L1.copy()
 6 >>> L2
 7 [10, [20, 21, 22], 30]
 8 >>> L1[0] = 9
 9 >>> L1
10 [9, [20, 21, 22], 30]
11 >>> L2
12 [10, [20, 21, 22], 30]
13 >>> L1[1][1] = 21.5
14 >>> L1
15 [9, [20, 21.5, 22], 30]
16 >>> L2
17 [10, [20, 21.5, 22], 30]
18 >>> 
list

 

            复制列表

                    两种:深拷贝和浅拷贝;

            浅拷贝(shallow  copy): L.copy()  和 L[ :] 切片复制是浅拷贝

            深拷贝(deep copy) : 将对象逐层复制(复制后对象完全独立)

 1 >>> import copy
 2 >>> L
 3 [20, 21.5, 2222]
 4 >>> L1
 5 [9, [20, 21.5, 2222], 30]
 6 >>> L2 =copy.deepcopy(L1)  #调用深拷贝函数进行复制
 7 >>> L2
 8 [9, [20, 21.5, 2222], 30]
 9 >>> L[2] = 25
10 >>> L
11 [20, 21.5, 25]
12 >>> L1
13 [9, [20, 21.5, 25], 30]
14 >>> L2
15 [9, [20, 21.5, 2222], 30]
16 >>> 
深拷贝

 

            del 运算符

                   用于删除列表元素;

 1 >>> cities = ['北京','上海','深圳']
 2 >>> cities.remove('深圳')
 3 >>> cities
 4 ['北京', '上海']
 5 >>> cities = ['北京','上海','深圳']
 6 >>> cities.pop(2)
 7 '深圳'
 8 >>> cities
 9 ['北京', '上海']
10 >>> cities = ['北京','上海','深圳']
11 >>> del cities[2]
12 >>> cities
13 ['北京', '上海']
14 >>> 
删除列表元素

 

 

练习:

 1 #!/usr/bin/python
 2 
 3 primes = [] #用来存放质数
 4 while True:
 5     n = int(input("请输入一个大于0的整数:"))
 6     if n <= 1:
 7         break #终止死循环
 8     for  x in range(2, n):
 9         if n % x == 0:
10             break   #不是质数(素数)
11     else:
12         print(n,"是质数")
13         primes.append(n) #存入列表
14 
15 print("所有质数:",primes)
16 print("end!")
17 >>> ================================ RESTART ================================
18 >>> 
19 请输入一个大于0的整数:2
20 2 是质数
21 请输入一个大于0的整数:3
22 3 是质数
23 请输入一个大于0的整数:4
24 请输入一个大于0的整数:5
25 5 是质数
26 请输入一个大于0的整数:0
27 所有质数: [2, 3, 5]
28 end!
29 >>> 
View Code

 

            列表是可迭代对象;(字符串也是可迭代对象)

 1 >>> L = [2,3,4,5,6,7]
 2 >>> for x in L:
 3     print(x)
 4 
 5     
 6 2
 7 3
 8 4
 9 5
10 6
11 7
12 >>> 
迭代

 

           

列表推导式(list comprehension)
列表推导式是用可迭代对象,依次生成列表内元素的方式。
语法:
[表达式 for 变量 in 可迭代对象]

[表达式 for 变量 in 可迭代对象 if 条件表达式]
例如:

1 >>> L = [x**2 for x in range(1,11)]
2 >>> L
3 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
4 >>> [x**2 for x in range(1,11,2)]
5 [1, 9, 25, 49, 81]
6 >>> 
list推导式

 

         列表推导式嵌套

                语法:[表达式1 for 变量1 in 可迭代对象1 (if 条件表达式1)表达式2 for 变量2 in 可迭代对象2 (if 条件表达式2)]

嵌套

 

           列表和字符串的比较:

                 1, 都是序列,有先后顺序; 2 列表是可变的,字符串是不变的;  3 列表可以存储任意类型的数,字符串只能存储字符;

           字符串的文本解析方法:

                 s.split( sep=None)    将字符串s分割成字符串列表;

                 s.join(iterable)          将可迭代对象进行拼接,中间用字符串进行分割;

 1 >>> 
 2 >>> s = "welcome to china"
 3 >>> words = s.split(' ')
 4 >>> print(words)
 5 ['welcome', 'to', 'china']
 6 >>> 
 7 >>> path = '/home/test/a.txt'
 8 >>> path.split('/')
 9 ['', 'home', 'test', 'a.txt']
10 >>> path.split('/')[-1]
11 'a.txt'
12 >>> s = 'AcBcDcE'
13 >>> s.split('c')
14 ['A', 'B', 'D', 'E']
15 >>> 
16 >>> l = ["C:","windows","system32"]
17 >>> '\\'.join(l)
18 'C:\\windows\\system32'
19 >>> print(s)
20 AcBcDcE
21 >>> s = '\\'.join(l)
22 >>> print(s)
23 C:\windows\system32
24 >>> 
View Code

 

           练习:

 1 >>> s = 'hello'
 2 >>> ' '.join(s)
 3 'h e l l o'
 4 >>> s1 = ' '.join(s)
 5 >>> print(s1)
 6 h e l l o
 7 >>> s1
 8 'h e l l o'
 9 >>> s2 = '-'.join(s)
10 >>> s2
11 'h-e-l-l-o'
12 >>> 
View Code

 

 

 

             

 

 

 

          

posted on 2018-04-30 22:39  微子天明  阅读(191)  评论(0编辑  收藏  举报

导航