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']
![](http://i2.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'
![](http://i2.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']
![](http://i2.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













本文转自Uniqueh51CTO博客,原文链接: http://blog.51cto.com/13363488/2056842,如需转载请自行联系原作者

相关文章
|
22天前
|
索引 Python
Python列表
Python列表。
44 8
|
25天前
|
C语言 Python
[oeasy]python054_python有哪些关键字_keyword_list_列表_reserved_words
本文介绍了Python的关键字列表及其使用规则。通过回顾`hello world`示例,解释了Python中的标识符命名规则,并探讨了关键字如`if`、`for`、`in`等不能作为变量名的原因。最后,通过`import keyword`和`print(keyword.kwlist)`展示了Python的所有关键字,并总结了关键字不能用作标识符的规则。
31 9
|
1月前
|
数据挖掘 大数据 数据处理
python--列表list切分(超详细)
通过这些思维导图和分析说明表,您可以更直观地理解Python列表切分的概念、用法和实际应用。希望本文能帮助您更高效地使用Python进行数据处理和分析。
64 14
|
1月前
|
数据挖掘 大数据 数据处理
python--列表list切分(超详细)
通过这些思维导图和分析说明表,您可以更直观地理解Python列表切分的概念、用法和实际应用。希望本文能帮助您更高效地使用Python进行数据处理和分析。
59 10
|
2月前
|
数据处理 开发者 Python
Python中的列表推导式:简洁高效的数据处理
在编程世界中,效率和可读性是代码的两大支柱。Python语言以其独特的简洁性和强大的表达力,为开发者提供了众多优雅的解决方案,其中列表推导式便是一个闪耀的例子。本文将深入探讨列表推导式的使用场景、语法结构及其背后的执行逻辑,带你领略这一特性的魅力所在。
|
2月前
|
开发者 Python
探索Python中的列表推导式:简洁而强大的工具
【10月更文挑战第41天】 在编程的世界中,效率与简洁是永恒的追求。本文将深入探讨Python编程语言中一个独特且强大的特性——列表推导式(List Comprehension)。我们将通过实际代码示例,展示如何利用这一工具简化代码、提升性能,并解决常见编程问题。无论你是初学者还是资深开发者,掌握列表推导式都将使你的Python之旅更加顺畅。
|
2月前
|
Python
探索Python中的列表推导式
【10月更文挑战第38天】本文深入探讨了Python中强大而简洁的编程工具——列表推导式。从基础使用到高级技巧,我们将一步步揭示如何利用这个特性来简化代码、提高效率。你将了解到,列表推导式不仅仅是编码的快捷方式,它还能帮助我们以更加Pythonic的方式思考问题。准备好让你的Python代码变得更加优雅和高效了吗?让我们开始吧!
|
2月前
|
Python
SciPy 教程 之 SciPy 模块列表 13
SciPy教程之SciPy模块列表13:单位类型。常量模块包含多种单位,如公制、二进制(字节)、质量、角度、时间、长度、压强、体积、速度、温度、能量、功率和力学单位。示例代码展示了如何使用`constants`模块获取零摄氏度对应的开尔文值(273.15)和华氏度与摄氏度的转换系数(0.5556)。
23 1
|
2月前
|
弹性计算 安全 数据处理
Python高手秘籍:列表推导式与Lambda函数的高效应用
列表推导式和Lambda函数是Python中强大的工具。列表推导式允许在一行代码中生成新列表,而Lambda函数则是用于简单操作的匿名函数。通过示例展示了如何使用这些工具进行数据处理和功能实现,包括生成偶数平方、展平二维列表、按长度排序单词等。这些工具在Python编程中具有高度的灵活性和实用性。
48 2
|
3月前
|
Python
SciPy 教程 之 SciPy 模块列表 9
SciPy教程之常量模块介绍,涵盖多种单位类型,如公制、质量、角度、时间、长度、压强等。示例展示了如何使用`scipy.constants`模块查询不同压强单位对应的帕斯卡值,包括atm、bar、torr、mmHg和psi。
22 1