Python中的列表

一.列表
定义:包含任意类型的元素,包括数值类型,列表,字符串等均可。
(1)定义一个空列表
In [1]: list = []
Python中的列表
(2)定义一个包含元素的列表
In [6]: list = ['hello', 2, 2.0, True, (1,'hello')]
Python中的列表
In [8]: list1 = ['hello', 2, 2.0, True, (1,'hello'), [1, 2, 3,4]]
Python中的列表
In [9]: print list1
['hello', 2, 2.0, True, (1, 'hello'), [1, 2, 3, 4]]
Python中的列表
#定义元组:
I```
n [11]: print t
('hello', 2, 2.0, True, (1, 'hello'), [1, 2, 3, 4])
In [13]: t[0] = 'world' #元组是不可变数据类型,不能修改元素;
TypeError Traceback (most recent call last)
<ipython-input-13-f60b24e075bb> in <module>()
----> 1 t[0] = 'world'

TypeError: 'tuple' object does not support item assignment
Python中的列表
In [14]: list[1] = 'world' #列表是可变数据类型可以修改元素
Python中的列表
In [15]: print list
['hello', 'world', 2.0, True, (1, 'hello'), [1, 2, 3, 4]]


1.索引:

n [16]: print list
['hello', 'world', 2.0, True, (1, 'hello'), [1, 2, 3, 4]]
Python中的列表

1)正向索引
In [19]: list[0]
Out[19]: 'hello'
Python中的列表
2)反向索引
In [20]: list[-1]
Out[20]: [1, 2, 3, 4]
Python中的列表
3)拿出列表的最后一个元素,最后一个元素是列表,再拿出列表的第四个元素,如下:
In [21]: list[-1][3]
Out[21]: 4
Python中的列表
2.切片
In [22]: list
Out[22]: ['hello', 'world', 2.0, True, (1, 'hello'), [1, 2, 3, 4]]
Python中的列表
1)去掉列表中的第一个元素
In [23]: list[1:]
Out[23]: ['world', 2.0, True, (1, 'hello'), [1, 2, 3, 4]]
Python中的列表
2)逆序显示
In [24]: list[::-1]
Out[24]: [[1, 2, 3, 4], (1, 'hello'), True, 2.0, 'world', 'hello']
Python中的列表
3.重复,连接
1)重复
In [25]: list *2
Out[25]:
['hello',
'world',
2.0,
True,
(1, 'hello'),
[1, 2, 3, 4],
'hello',
'world',
2.0,
True,
(1, 'hello'),
[1, 2, 3, 4]]
Python中的列表
2)连接
In [28]: list1
Out[28]: ['hello', 2, 2.0, True, (1, 'hello'), [1, 2, 3, 4]]
Python中的列表
In [29]: list + list1 #不建议使用
Out[29]:
['hello',
'world',
2.0,
True,
(1, 'hello'),
[1, 2, 3, 4],
'hello',
2,
2.0,
True,
(1, 'hello'),
[1, 2, 3, 4]]
Python中的列表
4.成员操作符(返回值为bool值)
In [30]: print list
['hello', 'world', 2.0, True, (1, 'hello'), [1, 2, 3, 4]]
Python中的列表
In [31]: print 1 in list
True

In [33]: print 'hello' in list
True

In [34]: print 2 in list
True
Python中的列表
In [35]: print not 2 in list
False
Python中的列表
四.列表的增删改查
#ip白名单
In [36]: allow_ip = ['172.25.254.1', '172.25.254.2', '172.25.254.100', '172.25.254.200']
In [37]: allow_ip.
allow_ip.append allow_ip.index allow_ip.remove
allow_ip.count allow_ip.insert allow_ip.reverse
allow_ip.extend allow_ip.pop allow_ip.sort
1.增
#当不知道功能时,找帮助
In [39]: help(allow_ip.append)
Python中的列表
Help on built-in function append:

append(...)
L.append(object) -- append object to end #追加元素到列表最后
Python中的列表
(1)追加元素到列表的最后

In [44]: allow_ip.append('172.25.254.25')

In [45]: print allow_ip
['172.25.254.1', '172.25.254.2', '172.25.254.100', '172.25.254.200', '172.25.254.25']
(2)增加元素到列表的指定位置
In [47]: help(allow_ip.insert)
Python中的列表
Help on built-in function insert:

insert(...)
L.insert(index(索引), object(对象)) -- insert object before index #添加对象到列表指定位置
Python中的列表

In [51]: print allow_ip
['172.25.254.10', '172.25.254.1', '172.25.254.2', '172.25.254.100', '172.25.254.200', '172.25.254.25']

(3)增加多个元素到列表最后
#iterable代表可迭代的
#目前学习的可迭代对象有:str, list, tuple
In [54]: for i in 'hello':
....: print i
....:
h
e
l
l
o

In [55]: for i in list:
   ....:     print i
   ....:     
hello
world
2.0
True
(1, 'hello')
[1, 2, 3, 4]
In [56]: for i in t:
   ....:     
   ....:     print i
   ....:     
hello
2
2.0
True
(1, 'hello')
[1, 2, 3, 4]

In [53]: help(allow_ip.extend)
Python中的列表
Help on built-in function extend:
Python中的列表
extend(...)
L.extend(iterable) -- extend list by appending elements from the iterable
(END) #增加列表可迭代对象
In [57]: allow_ip.extend(['172.25.254.20', '172.25.254.21'])
Python中的列表

In [58]: print allow_ip
['172.25.254.10', '172.25.254.1', '172.25.254.2', '172.25.254.100', '172.25.254.200', '172.25.254.25', '172.25.254.20', '172.25.254.21']
![](https://s1.51cto.com/images/blog/201801/02/939805a7ac3037461086dc3adc26c114.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
2.改

#通过列表的索引,对列表某个索引值重新赋值

In [59]: allow_ip[0] = '192.268.43.1'
![](https://s1.51cto.com/images/blog/201801/02/72945f9133d99b75e2659deefec654c4.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
In [60]: print allow_ip
['192.268.43.1', '172.25.254.1', '172.25.254.2', '172.25.254.100', '172.25.254.200', '172.25.254.25', '172.25.254.20', '172.25.254.21']
![](https://s1.51cto.com/images/blog/201801/02/a956fe1ade8e849591946fbe14af92bc.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)
3.查

In [62]: fruits = ['apple', 'banana', 'lemon', 'mango', 'banana']
(1)统计某个元素在列表中出现的次数:
In [63]: fruits.count('banana')
Out[63]: 2
Python中的列表
(2)找到某个值在列表中的索引值
In [65]: fruits.index('lemon')

Out[65]: 2
Python中的列表
4.删
(1)删除列表中遇到的第一个value值:
fruits = ['apple', 'banana', 'lemon', 'mango', 'banana']

In [66]: fruits.remove('banana')
Python中的列表
In [67]: print fruits
['apple', 'lemon', 'mango', 'banana']
Python中的列表
(2)删除列表中的第i个索引值
In [68]: fruits
Out[68]: ['apple', 'lemon', 'mango', 'banana']

In [72]: del fruits[0]
Python中的列表
In [73]: fruits
Out[73]: ['lemon', 'mango', 'banana']
Python中的列表
(3)删除除了第一个元素之外的其他索引
In [73]: fruits
Out[73]: ['lemon', 'mango', 'banana']

In [74]: del fruits[1:]
Python中的列表
In [75]: fruits
Out[75]: ['lemon']
Python中的列表
(4)删除列表对象
In [76]: del fruits

In [77]: fruits

NameError Traceback (most recent call last)
Python中的列表

Python中的列表(5)删除指定索引对应的值,默认是最后一个元素
In [80]: help(list.pop)

Help on built-in function pop:

pop(...)
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range. #删除指定索引对应的值,并返回删除的值,默认删除最后一个

In [78]: list = [1, 23, 56, 78, 23, 66]
#删除列表中的最后一个的值
In [81]: list.pop()
Out[81]: 66 #返回最后一个的值
Python中的列表
In [82]: print list
[1, 23, 56, 78, 23]
(6)删除列表的第一个元素
In [82]: print list
[1, 23, 56, 78, 23]
Python中的列表
In [83]: list.pop(0)
Out[83]: 1

In [84]: print list
[23, 56, 78, 23]

Python中的列表
5.其他的排序及逆序
(1)排序
#是数字的话,按照数字大小排序;
#是字母的话,按照ASCII码来排序;
#查看对应ASCII码:ord('a')
数字排序
In [86]: list
Out[86]: [23, 56, 78, 23]
In [89]: print list
[23, 23, 56, 78]
Python中的列表
(2)逆转
#两种方法
1)逆序显示
In [90]: list[::-1]
Out[90]: [78, 56, 23, 23]
2)逆序
n [91]: list.reverse()
In [92]: print list
[78, 56, 23, 23]

列表经典题型:
用户登录程序版本2:
-用户名和密码分别保存在列表中;
-用户登录时,判断该用户是否注册;
-用户登录时,为防止***暴力破解, 仅有三次机会;
-如果登录成功,显示登录成功(exit(), break).
知识点学习:
-python中特有的while....else...语句
-如果满足while后面的语句,执行while循环的程序, 如果不满足,执行else里面的程序.
提示: 用户名和密码一一对应users = ["user1", "user2", "user3"]
#参考代码一:

[root@localhost code1]# vim list.py
#!/usr/bin/env python
#coding:utf-8

users = ['user1', 'user2', 'user3']   #存储用户名的列表
passwds = ['123', '456', '789']       #存储密码的列表
count = 0
while count < 3:   #循环三次
        user = raw_input('请输入用户名:')
        if not user in users:    #判断用户是否在列表中
                print "该用户未注册"  
        break
    else:
                passwd = raw_input('请输入密码:')  #输入密码
                for i in users:   #遍历用户名是否在列表中
                        i = users.index(user)   #i索引值
                        for j in passwds:  #遍历密码是否在列表中
                                j = passwds.index(passwd)
                                if i == j:  #用户名和密码依次对应
                                        print 'successfully'
                                        exit()
        else:
                        print '登陆失败' 
                        count +=1
else:
        print '超过三次'

[root@localhost code1]# python list.py
请输入用户名:user2
请输入密码:123
登陆失败
请输入用户名:user1
请输入密码:456
登陆失败
请输入用户名:user3
请输入密码:123
登陆失败
超过三次
[root@localhost code1]# python list.py
请输入用户名:user1
请输入密码:123
successfully
#参考代码二:
[root@localhost code1]# python list1.py

#!/usr/bin/env python
#coding:utf-8
users = ['user1', 'user2', 'user3']
passwds = ['123', '456', '789']
count = 0
while count < 3:
        user = raw_input('请输入用户名:')
        if not user in users:
                print '用户未注册'
                break
        passwd = raw_input('请输入密码:')
        index = users.index(user)
        if passwd == passwds[index]:
                print 'successfully'
                break
        else:
                print '登陆失败'
                count +=1
else:
        print '超过三次'
~                                 

五.列表构建栈和队列数据结构
1.栈
-栈是先进后出(LIFO-first in last out);
-类似于往箱子里面放书;
-代码实现如下: (实际应用中这样太麻烦,将来会用类实现)
[root@localhost code1]# vim zhan.py
#!/usr/bin/env python
#coding:utf-8

stack = []
print '栈操作'.center(40,'*')
info = """
1.入栈
2.出栈
3.栈长度
4.查看栈
5.退出
请输入你的选择:"""

while True:
        choice = raw_input(info).strip()
        if choice == '1':
                print '入栈操作...' .center(40,"*")
                value = raw_input('请输入栈元素:')
                stack.append(value)
                print '元素%s入栈成功...' %(value)
        elif choice == '2':
                print '出栈操作...' .center(40,"*")
                if not stack:
                       print '栈为空'
                else:
                        item = stack.pop()
                print '元素%s出栈成功...' %(item)
        elif choice == '3':
                print '查看栈长度' .center(40,"*")
                print len(stack)
        elif choice == '4':
                print '查看栈元素'.center(40,"*")
                if not stack:
                        print '栈为空'
                else:
                        for i in stack:
                                print i,
        elif choice == '5':
                exit()
                print '退出...',center(40,'*')
     else:
                print '请输入正确的选择......'

[root@localhost code1]# python zhan.py

***栈操作****

1.入栈
2.出栈
3.栈长度
4.查看栈
5.退出

请输入你的选择:1
****入栈操作...*****
请输入栈元素:hello
元素hello入栈成功...

1.入栈
2.出栈
3.栈长度
4.查看栈
5.退出

请输入你的选择:2
****出栈操作...*****
元素hello出栈成功...

1.入栈
2.出栈
3.栈长度
4.查看栈
5.退出

请输入你的选择:3
****查看栈长度*****
0

1.入栈
2.出栈
3.栈长度
4.查看栈
5.退出

请输入你的选择:1
****入栈操作...*****
请输入栈元素:hello
元素hello入栈成功...

1.入栈
2.出栈
3.栈长度
4.查看栈
5.退出

请输入你的选择:3
****查看栈长度*****
1

1.入栈
2.出栈
3.栈长度
4.查看栈
5.退出

请输入你的选择:4
****查看栈元素*****
hello
1.入栈
2.出栈
3.栈长度
4.查看栈
5.退出
请输入你的选择:5
2.队列
-队列是先进先出(FIFO):
-类似于去餐厅买饭排队;
-代码实现如下:

[root@localhost code1]# vim duilie.py
#!/usr/bin/env python
#coding:utf-8
queue = []
print '队列操作'.center(40,'*')

info = """
        1.入队
        2.出队
        3.查看队
        4.退出
请输入你的选择:"""
while True:
choice = raw_input(info).strip()
        if choice == '1':
                print '入队操作...'.center(40,'*')
                value = raw_input('请输入入队元素:')
                queue.append(value)
                print '元素%s入队成功...' %(value)
        elif choice == '2':
                if not queue:
                        print '队为空'
                else:
                        print '出队操作...'.center(40,"*")
            item = queue.pop(0)
                        print '元素%s出队成功...'  %(item)

        elif choice == '3':
                if not queue:
                        print '队为空'
                else:
                        print '查看队列...'.center(40,'*')
                        for i in queue:
                                print i,

        elif choice == '4':
                exit()
    else:
                print '请输入正确选择......
[root@localhost code1]# python duilie.py 

**队列操作**

1.入队
2.出队
3.查看队
4.退出

请输入你的选择:1
****入队操作...*****
请输入入队元素:hello
元素hello入队成功...

1.入队
2.出队
3.查看队
4.退出

请输入你的选择:3
****查看队列...*
hello
1.入队
2.出队
3.查看队
4.退出
请输入你的选择:1
****入队操作...*

请输入入队元素:world
元素world入队成功...

1.入队
2.出队
3.查看队
4.退出

请输入你的选择:3
****查看队列...*
hello world
1.入队
2.出队
3.查看队
4.退出
请输入你的选择:2
****出队操作...*

元素hello出队成功...

1.入队
2.出队
3.查看队
4.退出

请输入你的选择:2
元素world出队成功...

1.入队
2.出队
3.查看队
4.退出

五.列表内置方法
-cmp
-min, max
-zip
In [2]: list = ['hello', 1, (1, 2, 3), ['hello', 2]]

In [3]: list1 = ['world', 2, (1,2), ['hello', 6]]

In [4]: zip(list, list1)
Out[4]: [('hello', 'world'), (1, 2), ((1, 2, 3), (1, 2)), (['hello', 2], ['hello', 6])]

-enumerate

真实场景的应用:

[root@localhost code1]# vim cards.py

#!/usr/bin/env python

#coding:utf-8
"""
卡号由 6 位组成, 前 3 位是 610 , 后面的依次是 001, 002, 003...100,将这些卡号用列
表保存起来
"""

cards = []
for i in range(1,101):  #i = 1,2,3,4...100
        a = '610%.3d'   %(i)   #a = 610001,610002...610100
        cards.append(a)
print cards  #cards是列表
#卡号显示,每十个卡号换行显示:

[root@localhost code1]# vim cards.py
#!/usr/bin/env python
#coding:utf-8
"""
卡号显示,每十个卡号换行显示:

"""

cards = []
for i in range(1,101):
        a = '610%.3d'   %(i)
        cards.append(a)
for i,j in enumerate(cards):
        if i%10 == 0:
                print
        print j,

[root@localhost code1]# python cards.py

610001 610002 610003 610004 610005 610006 610007 610008 610009 610010
610011 610012 610013 610014 610015 610016 610017 610018 610019 610020
610021 610022 610023 610024 610025 610026 610027 610028 610029 610030
610031 610032 610033 610034 610035 610036 610037 610038 610039 610040
610041 610042 610043 610044 610045 610046 610047 610048 610049 610050
610051 610052 610053 610054 610055 610056 610057 610058 610059 610060
610061 610062 610063 610064 610065 610066 610067 610068 610069 610070
610071 610072 610073 610074 610075 610076 610077 610078 610079 610080
610081 610082 610083 610084 610085 610086 610087 610088 610089 610090
610091 610092 610093 610094 610095 610096 610097 610098 610099 610100

转载于:https://blog.51cto.com/13363488/2056842

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值