您的位置:首页 > 编程语言 > Python开发

Python列表详解(二)

2016-08-19 00:51 281 查看

交互解释器

Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:40:30) [MSC v.1500 64 bit (
AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.


关于列表的操作

定义列表

>>> world = ['a','b','c',['qwer','asdf'],1,2,3,'ChangerLee']


下标正取值

>>> world[1]
'b'
>>> world[3]
['qwer', 'asdf']


下标反取值

>>> world[-2]
3


元素全选操作符

>>> world[:]
['a', 'b', 'c', ['qwer', 'asdf'], 1, 2, 3, 'ChangerLee']


元素片段操作

>>> world[2:]
['c', ['qwer', 'asdf'], 1, 2, 3, 'ChangerLee']
>>> world[:3]
['a', 'b', 'c']
>>> world[1:3]
['b', 'c']
>>>


列表的长度

>>> world
['a', 'b', 'c', ['qwer', 'asdf'], 1, 2, 3, 'ChangerLee']
>>> len(world)
8


id方法:查看python中对象内存序列的内建方法

>>> help(id)
Help on built-in function id in module __builtin__:

id(...)
id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory address.)


列表的复制

>>> world
['a', 'b', 'c', ['qwer', 'asdf'], 1, 2, 3, 'ChangerLee']
>>> anotherworld=world[:]
>>> id(world)
50136648L
>>> id(anotherworld)
50137992L


列表取别名

>>> world
['a', 'b', 'c', ['qwer', 'asdf'], 1, 2, 3, 'ChangerLee']
>>> sameworld=world
>>> id(world)
50136648L
>>> id(sameworld)
50136648L
>>>


列表的连接

>>> world
['a', 'b', 'c', ['qwer', 'asdf'], 1, 2, 3, 'ChangerLee']
>>> anotherworld+world
['a', 'b', 'c', ['qwer', 'asdf'], 1, 2, 3, 'ChangerLee', 'a', 'b', 'c', ['qwer',
'asdf'], 1, 2, 3, 'ChangerLee']
>>> [1,2,3]+[4,5,6]
[1, 2, 3, 4, 5, 6]
>>> list1
[5, 2, 3]
>>> list1*3
[5, 2, 3, 5, 2, 3, 5, 2, 3]
>>> list1
[5, 2, 3]


列表的逻辑操作

注意:列表的逻辑比较是列表的第一个元素的比较

>>> list1 = [1,2,3]
>>> list2 = [4,5,6]
>>> list1 < list2
True
>>> list1[0]=5
>>> list1
[5, 2, 3]
>>> list1 < list2
False


列表存在性判断not in 和in

>>> list2
[4, 5, 6]
>>> 5 in list2
True
>>> 3 not in list2
True


列表中的列表元素存在性判断

>>> list1 = [1,2,3,['a','b','c']]
>>> list1[3]
['a', 'b', 'c']
>>> 'a' in list1
False
>>> 'a' in list1[3]
True
>>> list1[3][2]
'c'
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息