第二课:List列表、Tuple元祖、Dict字典

Python 列表List

List

  1. 加号+是列表连接运算符,星号*是重复操作
>>> list = ['AA','BB','CC','DD']
>>> list[:3]
['AA', 'BB', 'CC']
>>> print list*2
['AA', 'BB', 'CC', 'DD', 'AA', 'BB', 'CC', 'DD']
>>> print list+['Hello']
['AA', 'BB', 'CC', 'DD', 'Hello']
  1. 列表元素的添加与删除
# -*- coding: UTF-8 -*-
list = ["Hello",1,3]
print list
list.append("Google")
print list
del list[2]
print list     

输出:

['Hello', 1, 3]
['Hello', 1, 3, 'Google']
['Hello', 1, 'Google']
  1. Python列表函数:
    3.1 cmp(list1, list2): 可直接使用,先比较字符,字符相同在比较长度,但在python3中不存在该函数,可以使用operator.eq()来实现
# -*- coding: UTF-8 -*-                                          
list1,list2 = [123,'xyz'],[456,'abc']
print cmp(list1,list2)
print cmp(list2,list1)
list3 = list1 + [786]
print cmp(list1,list3)
print cmp(list2,list3)

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
-1
1
-1
1

3.2 len()返回列表的长度,可直接使用
3.3 max()返回列表中元素的最大值,min()返回列表中元素的最小值,均可直接使用
3.4 list(Tuple)可将元祖转换为列表,可直接使用

# -*- coding: UTF-8 -*-                                          
aTuple = (123,'xyz','zara','abc')
print aTuple
aList = list(aTuple)
print aList

输出

helloworld@LG-virtual-machine:~/code$ python test.py 
(123, 'xyz', 'zara', 'abc')
[123, 'xyz', 'zara', 'abc']
  1. 列表的相关方法:
    4.1 list.append(obj):在列表末尾添加新的对象
    4.2 list.count(obj):统计某个元素在列表中出现的次数
    4.3 list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
    4.4 list.index(obj):从列表中找出某个值第一个匹配项的索引位置
    4.5 list.insert(obj):将对象插入列表
    4.6 list.pop([index=-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
    4.7 list.remove(obj):移除列表中某个值的第一个匹配项
    4.8 list.reverse():反向列表中元素
    4.9 list.sort(cmp=None, key=None, reverse=False):对原列表进行排序
# -*- coding: UTF-8 -*-                                          
aList = [123,'xyz','zara','abc',123]
print aList
aList.append(2009)
print aList
print aList.count(123)
aList.extend([1,2,3,4])
print aList
aList.insert(2,'uvw')
print aList
aList.pop()
print aList
aList.pop(3)
print aList
aList.remove(123)
print aList
aList.reverse()
print aList

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
[123, 'xyz', 'zara', 'abc', 123]
[123, 'xyz', 'zara', 'abc', 123, 2009]
2
[123, 'xyz', 'zara', 'abc', 123, 2009, 1, 2, 3, 4]
[123, 'xyz', 'uvw', 'zara', 'abc', 123, 2009, 1, 2, 3, 4]
[123, 'xyz', 'uvw', 'zara', 'abc', 123, 2009, 1, 2, 3]
[123, 'xyz', 'uvw', 'abc', 123, 2009, 1, 2, 3]
['xyz', 'uvw', 'abc', 123, 2009, 1, 2, 3]
[3, 2, 1, 2009, 123, 'abc', 'uvw', 'xyz']
  • list.sort(cmp=None, key=None, reverse=False),cmp: 可选参数, 如果指定了该参数会使用该参数的方法进行排序;key:主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序;reverse:reverse = True 降序, reverse = False 升序(默认)。
# -*- coding: UTF-8 -*-                                          
aList = [123,'Google','Taobao','Facebook']
aList.sort()
print aList

letters = ['e','a','b','d','c']
letters.sort(reverse=True)
print letters

def takeSecond(elem):
    return elem[1]
random = [(2,5),(3,1),(4,2),(1,3),(5,4)]
random.sort(key=takeSecond,reverse=True)
print random

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
[123, 'Facebook', 'Google', 'Taobao']
['e', 'd', 'c', 'b', 'a']
[(2, 5), (5, 4), (1, 3), (4, 2), (3, 1)]

Python 元祖Tuple

  1. 元祖用()标志,内部元素用逗号隔开,但是元祖不能二次赋值,相当于只读列表
>>> tuple=('AA','BB','CC','DD')
>>> print tuple
('AA', 'BB', 'CC', 'DD')
>>> tuple[2]=1000
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> tuple[2:]
('CC', 'DD')
>>> print tuple+['Hello']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
>>> print tuple+('Hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
>>> print tuple+('Hello',)
('AA', 'BB', 'CC', 'DD', 'Hello')
>>> tuple[2:2]
()
>>> tuple[2:3]
('CC',)
  1. 元祖中的元素值是不允许修改的,但是我们可以对元祖进行连接组合
# -*- coding: UTF-8 -*-
tup1 = (12,34,56)                                                
tup2 = ('abc','xyz')

tup1 += tup2
print tup1

输出结果:

helloworld@LG-virtual-machine:~/code$ python test.py 
(12, 34, 56, 'abc', 'xyz')
  1. 元祖里面的元素值是不允许删除的,但是可以使用del语句来删除整个元祖
# -*- coding: UTF-8 -*-                                          
tup1 = (12,34,56)
print tup1
del tup1
print "after deleting tup1:",tup1

输出结果:可以看到在del删除之后已经无法访问了

helloworld@LG-virtual-machine:~/code$ python test.py 
(12, 34, 56)
after deleting tup1:
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print "after deleting tup1:",tup1
NameError: name 'tup1' is not defined
  1. 元祖运算符
Python表达式 结果 描述
len((1,2,3)) 3 计算元素个数
(1,2,3)+(4,5,6) (1,2,3,4,5,6) 连接
("hello",)*4 ("hello","hello","hello","hello") 复制
3 in (1,2,3) True 判断元素是否存在元祖中
for x in (1,2,3):print x, 1,2,3 迭代
  1. 任何无符号的对象,以逗号隔开,默认为元祖
# -*- coding: UTF-8 -*-                                          
print 'abc', -4.24e93, 18+6.6j, 'xyz'

x, y = 1, 2
print "value of x,y:",x,y 

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
abc -4.24e+93 (18+6.6j) xyz
value of x,y: 1 2

Python字典

字典用{}标志,由索引key和它对应的值value组成,与列表的区别在于:列表是有序的对象集合,字典是无序的对象集合,列表中的元素通过偏移下标来取,而字典中的元素是通过键值来存取的。

>>> dict = {}
>>> dict
{}
>>> dict['one']="This is one"
>>> dict
{'one': 'This is one'}
>>> dict[2]=2.0
>>> dict
{2: 2.0, 'one': 'This is one'}
>>> print dict['one']
This is one
>>> print dict[2]
2.0
>>> print dict.keys()
[2, 'one']
>>> print dict.values()
[2.0, 'This is one']
  1. 字典元素的删除
dict = {'Name':'Tom','Age':7,'Class':'First'}
print dict
del dict['Name']#删除键是'Name'的条目
print dict
dict.clear()#清空词典的所有条目
del dict#删除词典
print dict#dict被删除后,这里解释器认为这是关键词dict,所以输出type
helloworld@LG-virtual-machine:~/code$ python test.py 
{'Age': 7, 'Name': 'Tom', 'Class': 'First'}
{'Age': 7, 'Class': 'First'}
<type 'dict'>
  1. 字典相关函数的使用:
    3.1 cmp(dict,dict)
# -*- coding: UTF-8 -*-
dict1 = {'Name':'Tom','Age':7,'Class':'First'}
dict2 = {'Name':'Jack','Age':5,'Class':'Second'}
dict3 = {'name':'Tom','Age':7,'Class':'First'}

print "Return value:%d"%cmp(dict1,dict2)
print "Return value:%d"%cmp(dict1,dict3)             

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Return value:1
Return value:-1

3.2 len():计算字典元素个数,即键的总数;
3.3 str():输出字典可打印的字符串表示
3.4 type()返回输入变量的类型,如果是字典就返回字典类型

# -*- coding: UTF-8 -*-                                          
dict1 = {'Name':'Tom','Age':7,'Class':'First'}
print dict1
print str(dict1)
print len(dict1)
print type(dict1)

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
{'Age': 7, 'Name': 'Tom', 'Class': 'First'}
{'Age': 7, 'Name': 'Tom', 'Class': 'First'}
3
<type 'dict'>
  1. 字典的内置方法:
    4.1 dict.clear():删除字典内的所有元素
    4.2 dict.copy():返回字典的浅复制
    4.3 dict.fromkeys(seq[,val]):创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
# -*- coding: UTF-8 -*-
seq = ('Google', 'Facebook','Apple')                             

dic = dict.fromkeys(seq)
print "新字典:%s"%str(dic)

dic1 = dict.fromkeys(seq,10)
print dic1

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
新字典:{'Google': None, 'Facebook': None, 'Apple': None}
{'Google': 10, 'Facebook': 10, 'Apple': 10}

4.4 dict.get(key,default=None):返回函数指定键的值,如果值不存在则返回默认值
4.5 dict.has_key(key):函数用于判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false。

# -*- coding: UTF-8 -*-                                          
dict1 = {'Name':'Tom','Age':20}

print "value:%s"%dict1.get('Age')
print "value:%s"%dict1.get('Class')
print "value:%s"%dict1.get('Class','No')

print "value:%s"%dict1.has_key('Class')
print "value:%s"%dict1.has_key('Age')

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
value:20
value:None
value:No
value:False
value:True

4.6 dict.item():以列表返回可遍历的(key,value)元祖数组
4.7 dict.keys():以列表返回一个字典所有的键
4.7.1 dict.values():以列表返回一个字典所有的值

# -*- coding: UTF-8 -*-                                          
dict1 = {'Name':'Tom','Age':20,'class':'First'}
print dict1.items()

for key,value in dict1.items():
    print key,value
print dict1.keys()
print dict1.values()

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
[('Age', 20), ('Name', 'Tom'), ('class', 'First')]
Age 20
Name Tom
class First
['Age', 'Name', 'class']
[20, 'Tom', 'First']

4.8 dict.setdefault(key,default=None)🔑查找的键值;default:键不存在时,设置的默认键值;如果字典中包含有给定键,则返回该键对应的值,否则返回该键设置的值

# -*- coding: UTF-8 -*-
dict1 = {'Name':'Tom','Age':20,'class':'First'}                  

print dict1.setdefault('Name','Jack') #这里并不会更改 Tom 为 Jack

print dict1.setdefault('gender','Male')

print dict1

输出:

Tom
Male
{'gender': 'Male', 'Age': 20, 'Name': 'Tom', 'class': 'First'}

4.9 dict.update(dict2):把dict2的键/值对更新到dict里

# -*- coding: UTF-8 -*-
dict1 = {'Name':'Tom','Age':20,'class':'First'}

dict2 = {'Name':'Jack','Gender':'Male'}

dict1.update(dict2)              
print dict1

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
{'Gender': 'Male', 'Age': 20, 'Name': 'Jack', 'class': 'First'}

4.10 dict.pop(key[,default]):删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值

# -*- coding: UTF-8 -*-
dict1 = {'Name':'Tom','Age':20,'class':'First'}

temp = dict1.pop('Name',None)
temp1 = dict1.pop('gender',None)
print temp
print temp1                                                      
print dict1

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
Tom
None
{'Age': 20, 'class': 'First'}

4.10 dict.popitem():随机返回并删除字典中的一对键和值。如果字典已经为空,却调用了此方法,就报出KeyError异常

# -*- coding: UTF-8 -*-                                          
dict1 = {'Name':'Tom','Age':20,'class':'First'}

temp = dict1.popitem()
print temp
print dict1

输出:

helloworld@LG-virtual-machine:~/code$ python test.py 
('Age', 20)
{'Name': 'Tom', 'class': 'First'}
posted @ 2018-08-21 19:59  默写年华  阅读(181)  评论(0编辑  收藏  举报