Python列表:
列表是最通用的Python复合数据类型。列表中包含以逗号分隔,并在方括号([])包含的项目。在一定程度上,列表相似C语言中的数组,它们之间的一个区别是,所有属于一个列表中的项目可以是不同的数据类型的。
存储在一个列表中的值可以使用切片操作符来访问([]和[:])用索引从0开始,在列表的开始位置和结束为-1。加号(+)符号列表连接运算符,星号(*)重复操作。例如:
#!/usr/bin/python
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists这将产生以下结果:
['abcd', 786, 2.23, 'john', 70.200000000000003]
abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
删除列表中的值
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
del list[0] #删除列表的第一个值获取列表长度
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
lenlist=len(list)列表遍历
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
for element in list:
print element
Python元组:
元组是类似于列表中的序列数据类型。一个元组由数个逗号分隔的值。不同于列表,不过,元组圆括号括起来。
列表和元组之间的主要区别是:列表括在括号([])和它们的元素和大小是可以改变的,而元组在圆括号(),不能被更新。元组可以被认为是只读列表。例如:
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists这将产生以下结果:
('abcd', 786, 2.23, 'john', 70.200000000000003)
abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
以下是元组无效的,因为我们尝试更新一个元组,这是不允许的。类似的操作在列表中是可以的:
#!/usr/bin/python
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list注意:元组中只包含一个元素时,需要在元素后面添加逗号来消除歧义:tup1=(55,)
Python字典:
Python字典是一种哈希表型。他们像关联数组或哈希在Perl中一样,由键 - 值对组成。字典键几乎可以是任何Python类型,但通常是数字或字符串。值可以是任意Python的对象。
字典是由花括号括号({}),可分配值,并用方括号([])访问。例如:
#!/usr/bin/python
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print dict['one'] # Prints value for 'one' key
print dict[2] # Prints value for 2 key
print tinydict # Prints complete dictionary
print tinydict.keys() # Prints all the keys
print tinydict.values() # Prints all the values这将产生以下结果:
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
字典有元素顺序的概念。它的元素是无序的。
总结:
1、列表使用中括号[],元组使用小括号(),字典使用大括号{}
2、列表和字典值可以被更改,元组的不能被更改
















