|
列表
#访问列表中的值
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print "list1[0]: ", list1[0] #list1[0]: physics
print "list2[1:5]: ", list2[1:5] #list2[1:5]: [2, 3, 4, 5]
#删除列表元素
list1 = ['physics', 'chemistry', 1997, 2000]
print list1 #['physics', 'chemistry', 1997, 2000]
del list1[2]
print "After deleting value at index 2 : "
print list1 #['physics', 'chemistry', 2000]
#Python列表脚本操作符
print len([1, 2, 3]) #3
print [1, 2, 3] + [4, 5, 6] #[1, 2, 3, 4, 5, 6]
print ['Hi!'] * 4 #['Hi!', 'Hi!', 'Hi!', 'Hi!']
print 3 in [1, 2, 3]
for x in [1, 2, 3]: print x # 1 2 3
#列表的切片
a[1:] #片段操作符等价于a[1:len(a)-1:1],:后面省略,表示切到列表的末尾,步长为1则可以省略
a[:] #等价于a[0:] ,:前面是0可以省略
[1,2]+[3,4] #同extend()
[2]*4 #为 [2,2,2,2]
del l[2] #删除指定下标的元素
del list[1:3] #删除指定下标范围的元素
list的复制
list1=list2 #list2的别名,对list1操作,即对list2操作
list1=list2[:] #生成list2的一个copy
#列表的内置方法
# cmp 函数
ist1, list2 = [123, 'xyz'], [456, 'abc']
print cmp(list1, list2) #-1
print cmp(list2, list1) #1
list3 = list2 + [786];
print cmp(list2, list3) #-1
import operator #Python 3.X 的版本中已经没有 cmp 函数,如果你需要实现比较功能,需要引入 operator 模块,适合任何对象
print operator.eq('hello', 'name')
# len函数
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1) #First list length : 3
print "Second list length : ", len(list2) #Second list length : 2
# min max 函数
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print "Max value element : ", max(list1) #Max value element : zara
print "Max value element : ", max(list2) #Max value element : 700
print "min value element : ", min(list1) #min value element : 123
print "min value element : ", min(list2) #min value element : 200
# list 函数 用于将元组转换为列表
aTuple = (123, 'xyz', 'zara', 'abc');
aList = list(aTuple)
print "列表元素 : ", aList #列表元素 : [123, 'xyz', 'zara', 'abc']
列表的方法
help(list.append)
增加:
insert L.insert(index, object) -- insert object before index 用于将指定对象插入列表的指定位置。
aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009)
print "Final List : ", aList #Final List : [123, 'xyz', 'zara', 2009, 'abc']
append L.append(object) -- append object to end 追加元素
aList = [123, 'xyz', 'zara', 'abc']
aList.append(2009)
print "Updated List : ", aList #Updated List : [123, 'xyz', 'zara', 'abc', 2009]
extend L.extend(iterable) -- extend list by appending elements from the iterable 追加list 用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
aList = [123, 'xyz', 'zara', 'abc', 123];
bList = [2009, 'manni'];
aList.extend(bList)
aList.extend('python')
print "Extended List : ", aList #Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni', 'p', 'y', 't', 'h', 'o', 'n']
删除
remove 删除第一次出现的元素,该方法没有返回值但是会移除列表中的某个值的第一个匹配项
L.remove(value) -- remove first occurrence of value
Raises ValueError if the value is not present.
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.remove('xyz');
print "List : ", aList; #List : [123, 'zara', 'abc', 'xyz']
aList.remove('abc');
print "List : ", aList; #List : [123, 'zara', 'xyz']
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.
list1 = ['Google', 'Runoob', 'Taobao']
list_pop=list1.pop(1)
print "删除的项为 :", list_pop #删除的项为 : Runoob
print "列表现在为 : ", list1 #列表现在为 : ['Google', 'Taobao']
查找:
index 返回元素的位置,无则抛异常
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
aList = [123, 'xyz', 'zara', 'abc']
print "Index for xyz : ", aList.index( 'xyz' ) #Index for xyz : 1
print "Index for zara : ", aList.index( 'zara' ) #Index for zara : 2
count L.count(value) -> integer -- return number of occurrences of value 统计元素在列表中出现的个数,如果没有就是0
aList = [123, 'xyz', 'zara', 'abc', 123];
print "Count for 123 : ", aList.count(123); #Count for 123 : 2
print "Count for zara : ", aList.count('zara'); #Count for zara : 0
修改:
reverse 反向列表中元素
L.reverse() -- reverse *IN PLACE* 倒序
aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.reverse()
print "List : ", aList; #List : ['xyz', 'abc', 'zara', 'xyz', 123]
sort 用于对原列表进行排序,如果指定参数,则使用比较函数指定的比较函数。
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.sort()
print "List : ", aList #List : [123, 'abc', 'xyz', 'xyz', 'zara']
元组:
创建空元组
tup1 = () 元组中只包含一个元素时,需要在元素后面添加逗号
tup1 = (50,) 访问元组
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )
print "tup1[0]: ", tup1[0] #tup1[0]: physics
print "tup2[1:5]: ", tup2[1:5] #tup2[1:5]: (2, 3, 4, 5)
修改元组
元组中的元素值是不允许修改的,但我们可以对元组进行连接组合,如下实例:
tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');
# 以下修改元组元素操作是非法的。
# tup1[0] = 100; # 创建一个新的元组
tup3 = tup1 + tup2;
print tup3; #(12, 34.56, 'abc', 'xyz')
删除元组
元组中的元素值是不允许删除的,但我们可以使用del语句来删除整个元组,如下实例:
tup = ('physics', 'chemistry', 1997, 2000);
print tup; #('physics', 'chemistry', 1997, 2000)
del tup;
print "After deleting tup : "
print tup; #NameError: name 'tup' is not defined
元组运算符
len((1, 2, 3))3
(1, 2, 3) + (4, 5, 6)(1, 2, 3, 4, 5, 6)
('Hi!',) * 4('Hi!', 'Hi!', 'Hi!', 'Hi!')
3 in (1, 2, 3)True
for x in (1, 2, 3): print x
元组索引,截取
因为元组也是一个序列,所以我们可以访问元组中的指定位置的元素,也可以截取索引中的一段元素,如下所示:
元组:
L = ('spam', 'Spam', 'SPAM!')
L[2] #'SPAM!'
L[-2] #'Spam'
L[1:] #('Spam', 'SPAM!')
无关闭分隔符,任意无符号的对象,以逗号隔开,默认为元组,如下实例:
print 'abc', -4.24e93, 18+6.6j, 'xyz'; #abc -4.24e+93 (18+6.6j) xyz
x, y = 1, 2;
print "Value of x , y : ", x,y; #Value of x , y : 1 2
元组内置函数
cmp(tuple1, tuple2)
tuple1, tuple2 = (123, 'xyz'), (456, 'abc')
print cmp(tuple1, tuple2) # -1
print cmp(tuple2, tuple1) #1
tuple3 = tuple2 + (786,)
print cmp(tuple2, tuple3) #-1
tuple4 = (123, 'xyz')
print cmp(tuple1, tuple4) #0
len(tuple) max(tuple) min(tuple)
tuple1, tuple2 = (123, 'xyz', 'zara', 'abc'), (456, 700, 200)
print "First tuple length : ", len(tuple1); #First tuple length : 4
print "Second tuple length : ", len(tuple2); # Second tuple length : 3
print "min value element : ", min(tuple1); #min value element : 123
print "min value element : ", min(tuple2); #min value element : 200
print "Max value element : ", max(tuple1); #Max value element : zara
print "Max value element : ", max(tuple2); #Max value element : 700
tuple(seq) 将列表转换为元组。
print tuple([1,2,3,4])
print tuple({1:2,3:4}) #针对字典 会返回字典的key组成的tuple (1, 3)
print tuple((1,2,3,4)) #元组会返回元组自身
元组的方法:
count T.count(value) -> integer -- return number of occurrences of value
aTuple = (123, 'xyz', 'zara', 'abc', 123);
print "Count for 123 : ", aTuple.count(123); #Count for 123 : 2
print "Count for zara : ", aTuple.count('zara'); #Count for zara : 1
index
T.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
bTuple = (123, 'xyz', 'zara', 'abc')
print "Index for xyz : ", bTuple.index( 'xyz' ) #Index for xyz : 1
print "Index for zara : ", bTuple.index( 'zara' ) #Index for zara : 2
字典
访问字典里的值
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name'] ## dict['Name']: Zara
print "dict['Age']: ", dict['Age'] #dict['Age']: 7
print "dict['Alice']: ", dict['Alice'] #KeyError: 'Alice'
修改字典
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']; #dict['Age']: 8
print "dict['School']: ", dict['School']; #dict['School']: DPS School
删除字典元素
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name'] # 删除键是'Name'的条目
dict.clear() # 清空词典所有条目
del dict # 删除词典
print "dict['Age']: ", dict['Age'] #TypeError: 'type' object has no attribute '__getitem__'
print "dict['School']: ", dict['School'] #TypeError: 'type' object has no attribute '__getitem__'
字典键的特性
1)不允许同一个键出现两次。创建时如果同一个键被赋值两次,后一个值会被记住,如下实例:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name'] #dict['Name']: Manni
2)键必须不可变,所以可以用数字,字符串或元组充当,所以用列表就不行,如下实例:
dict = {['Name']: 'Zara', 'Age': 7};
print "dict['Name']: ", dict['Name']; #TypeError: unhashable type: 'list'
字典内置函数
cmp()函数 优先级为元素个数,键大小,值大小
dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = {'Name': 'Mahnaz', 'Age': 27};
dict3 = {'Name': 'Abid', 'Age': 27};
dict4 = {'Name': 'Zara', 'Age': 7};
print "Return Value : %d" % cmp (dict1, dict2) #Return Value : -1
print "Return Value : %d" % cmp (dict2, dict3) #Return Value : 1
print "Return Value : %d" % cmp (dict1, dict4) #Return Value : 0
len()函数
dict = {'Name': 'Zara', 'Age': 7};
print "Length : %d" % len (dict) #Length : 2
str()函数
dict = {'Name': 'Zara', 'Age': 7};
print "Equivalent String : %s" % str (dict) #Equivalent String : {'Age': 7, 'Name': 'Zara'}
type()函数
dict = {'Name': 'Zara', 'Age': 7};
print "Variable Type : %s" % type (dict) #Variable Type : <type 'dict'>
增加:
dict.fromkeys() dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None.
创建一个新字典,以序列S中元素做字典的键,v为字典所有键对应的初始值。
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print "New Dictionary : %s" % str(dict) #New Dictionary : {'age': None, 'name': None, 'sex': None}
dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" % str(dict) #New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
删除:
dict.clear() -> D.clear() -> None. Remove all items from D.
dict = {'Name': 'Zara', 'Age': 7};
print "Start Len : %d" % len(dict) #Start Len : 2
dict.clear()
print "End Len : %d" % len(dict) #End Len : 0
dict.pop() D.pop(k[,d]) -> v, remove specified key and return the corresponding value. 删除字典给定键 key 所对应的值,返回值为被删除的值。key值必须给出。 否则,返回default值。
If key is not found, d is returned if given, otherwise KeyError is raised
site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
pop_obj=site.pop('name','高手教程') #如果key不存在,返回高手教程
print pop_obj # 输出 :菜鸟教程
print str(site) #{'url': 'www.runoob.com', 'alexa': 10000}
dict.popitem() 随机返回并删除字典中的一对键和值。如果字典已经为空,却调用了此方法,就报出KeyError异常。
D.popitem() -> (k, v), remove and return some (key, value) pair as a
2-tuple; but raise KeyError if D is empty.
site= {'name': '菜鸟教程', 'alexa': 10000, 'url': 'www.runoob.com'}
pop_obj=site.popitem()
print(pop_obj) #('url', 'www.runoob.com')
print(site) #{'alexa': 10000, 'name': '\xe8\x8f\x9c\xe9\xb8\x9f\xe6\x95\x99\xe7\xa8\x8b'}
修改:
dict.setdefault() 和get() 方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值。
D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
dict = {'runoob': '菜鸟教程', 'google': 'Google 搜索'}
print "Value : %s" % dict.setdefault('runoob', None) #Value : 菜鸟教程
print "Value : %s" % dict.setdefault('Taobao', '淘宝') #Value : 淘宝
print str(dict)
dict.update() 把字典dict2的键/值对更新到dict里。 有则修改,没有则添加
dict = {'Name': 'Zara', 'Age': 7,'Sex':'male'}
dict2 = {'Sex': 'female' }
dict.update(dict2)
print "Value : %s" % dict #Value : {'Age': 7, 'Name': 'Zara', 'Sex': 'female'}
dict.copy() -> D.copy() -> a shallow copy of D 返回一个字典的浅复制
dict1 = {'Name': 'Zara', 'Age': 7}
dict2 = dict1.copy()
print "New Dictinary : %s" % str(dict2) #
dict1 = {'user':'runoob','num':[1,2,3]}
dict2 = dict1 # 浅拷贝: 引用对象
dict3 = dict1.copy() # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
# 修改 data 数据
dict1['user']='root'
dict1['num'].remove(1)
# 输出结果
print(dict1) #{'num': [2, 3], 'user': 'root'}
print(dict2) #{'num': [2, 3], 'user': 'root'}
print(dict3) #{'num': [2, 3], 'user': 'runoob'}
深度复制:
import copy
dict1 = {'user':'runoob','num':[1,2,3]}
dict2 = dict1 # 浅拷贝: 引用对象
dict3 = dict1.copy() # 浅拷贝:深拷贝父对象(一级目录),子对象(二级目录)不拷贝,还是引用
dict4 = copy.deepcopy(dict1) #对象拷贝,深拷贝
# 修改 data 数据
dict1['user']='root'
dict1['num'].remove(1)
# 输出结果
print(dict1) #{'num': [2, 3], 'user': 'root'}
print(dict2) #{'num': [2, 3], 'user': 'root'}
print(dict3) #{'num': [2, 3], 'user': 'runoob'}
print(dict4) #{'num': [1, 2, 3], 'user': 'runoob'}
深度和浅度拷贝同时适合于列表
import copy
a = [1, 2, 3, 4, ['a', 'b']] #原始对象
b = a #赋值,传对象的引用,赋值引用,a 和 b 都指向同一个对象。
c = copy.copy(a) #对象拷贝,浅拷贝, 浅拷贝, a 和 b 是一个独立的对象,但他们的子对象还是指向统一对象(是引用)
d = copy.deepcopy(a) #对象拷贝,深拷贝,深度拷贝, a 和 b 完全拷贝了父对象及其子对象,两者是完全独立的。
a.append(5) #修改对象a
a[4].append('c') #修改对象a中的['a', 'b']数组对象
print 'a = ', a #a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
print 'b = ', b #b = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
print 'c = ', c #c = [1, 2, 3, 4, ['a', 'b', 'c']]
print 'd = ', d #d = [1, 2, 3, 4, ['a', 'b']]
查找:
dict.get() D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. 返回指定键的值,如果值不在字典中返回默认值。
dict = {'Name': 'Zara', 'Age': 27}
print "Value : %s" % dict.get('Age') #Value : 27
print "Value : %s" % dict.get('Sex', "Never") #Value : Never
dict.has_key() D.has_key(k) -> True if D has a key k, else False 判断键是否存在于字典中,如果键在字典dict里返回true,否则返回false。
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.has_key('Age') #Value : True
print "Value : %s" % dict.has_key('Sex') #Value : False
view的相关方法,返回的是view object,它可以反映出 dictionary 的变化,字典被修改了也能遍历,而其他的遍历方法会报错
dict.viewitems() D.viewitems() -> a set-like object providing a view on D's items
dict.viewkeys() D.viewkeys() -> a set-like object providing a view on D's keys
dict.viewvalues() D.viewvalues() -> an object providing a view on D's values
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.viewkeys() # Value : dict_keys(['Age', 'Name'])
print "Value : %s" % dict.viewitems() #Value : dict_items([('Age', 7), ('Name', 'Zara')])
print "Value : %s" % dict.viewvalues() #Value : dict_values([7, 'Zara'])
for value in dict.viewvalues():
print value #7 Zara
for items in dict.viewitems():
print items #('Age', 7) ('Name', 'Zara')
for key in dict.viewkeys():
print key #Age Name
dict.items() D.items() -> list of D's (key, value) pairs, as 2-tuples 以列表返回可遍历的(键, 值) 元组数组
dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}
print "字典值 : %s" % dict.items() #字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
# 遍历字典列表
for key,values in dict.items():
print key,values
'''
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
'''
dict.keys() D.keys() -> list of D's keys 返回一个字典所有的键
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.keys() #Value : ['Age', 'Name']
dict.values() D.values() -> list of D's values 以列表返回字典中的所有值。
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.values() #Value : [7, 'Zara']
dict.iteritems() D.iteritems() -> an iterator over the (key, value) items of D 用法和items()一样,只不过返回的是一个迭代器
dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}
print type(dict.iteritems()) #<type 'dictionary-itemiterator'>
print type(dict.items()) #<type 'list'>
# 遍历字典列表
for key,values in dict.iteritems():
print key,values
'''
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
'''
dict.iterkeys() D.iterkeys() -> an iterator over the keys of D 用法和keys()一样,只不过返回的是一个迭代器
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.iterkeys() #Value : <dictionary-keyiterator object at 0x00000000025D8E58>
for i in dict.iterkeys():
print i
dict.itervalues() D.itervalues() -> an iterator over the values of D 用法和values()一样,只不过返回的是一个迭代器
dict = {'Name': 'Zara', 'Age': 7}
print "Value : %s" % dict.itervalues() #Value : <dictionary-valueiterator object at 0x0000000002788E58>
for value in dict.itervalues():
print value
遍历:采用第一种遍历方法即可
for i in name_info: #循环key,效率高
print i,name_info
for i ,k in name_info.items(): #循环key和value,效率低,先要转换成列表
print i,k |
|