python-list

来源:互联网 发布:工厂模式编写js 编辑:程序博客网 时间:2024/05/17 22:14
checklist=["Microsoft Windows 7","CentOS Linux 3"]**遍历列表**for i in xrange(len(checklist)):    print checklist[i],type(checklist[i])print "列表长度:",len(checklist)**#列表过滤**list1=[1,2,3,4,5,6,7,8]list2=[1,2,3,4]for l in list1:    if l not in list2:        list2.append(l)print list2ll3=[5,6,7,8]N=[]for i in list1:    if i not in ll3:        N.append(i)print "N:",Nresult:Microsoft Windows 7 <type 'str'>CentOS Linux 3 <type 'str'>列表长度: 2[1, 2, 3, 4, 5, 6, 7, 8]N: [1, 2, 3, 4]list3=[1,6,2,3,15,4,3,7,8,2,1]print list3,len(list3)**#列表排序,并去重**l=list(set(list3))print l,len(l)# [1, 6, 2, 3, 15, 4, 3, 7, 8, 2, 1] 11# [1, 2, 3, 4, 6, 7, 8, 15] 8**#列表排序,不去重**list4=[1,6,2,3,15,4,3,7,8,2,1]print list4list4.sort()print list4# [1, 6, 2, 3, 15, 4, 3, 7, 8, 2, 1]# [1, 1, 2, 2, 3, 3, 4, 6, 7, 8, 15]**#列表不排序 去重**list5 = [1,4,3,3,4,2,3,4,5,6,1,8,8,8,8,8]func=lambda x,y:x if y in x else x+[y]print "func=",reduce(func,[[],]+list5)# func= [1, 4, 3, 2, 5, 6, 8]l=["this is list"]**#根据索引取出列表的值**print l[0]print l[0]==["this is list"]print l[0]=="this is list"# this is list# False# Truel6=[11,22,44,66,77]l7=[3,6,8,9,777]**#列表插入列表**l6.append(l7)print "l6:",l6print "l7:",l7# l6: [11, 22, 44, 66, 77, [3, 6, 8, 9, 777]]# l7: [3, 6, 8, 9, 777]**#列表合并**l8=[999,333,666,777]print l7+l8# [3, 6, 8, 9, 777, 999, 333, 666, 777]List=[{"id": "26721"}, {"id": 27.300}, {"id": 28543}]**#遍历列表  获取字典的值  获取列表元素类型**for i in List:    print i,i.get("id"),type(i)# {'id': '26721'} 26721 <type 'dict'># {'id': 27.3} 27.3 <type 'dict'># {'id': 28543} 28543 <type 'dict'>N=[]N2=[]M=[]M2=[]M3=[]List=[{"aaa":111},{"bbb":222},{"ccc":333}]for i in List:    N.append(i.values())#i.values() 返回值是list    N2.append(i.values()[0])#取出列表中每个字典的值,存放到N2中    M+=i#将列表元素的键放到列表中去    M2.append(i)#将每个键值对添加到M2中    M3+=i.keys()#效果等价于操作M    print i,i.values()# {'aaa': 111} [111]# {'bbb': 222} [222]# {'ccc': 333} [333]print Nprint N2print Mprint M2print M3# [[111], [222], [333]]# [111, 222, 333]# ['aaa', 'bbb', 'ccc']# [{'aaa': 111}, {'bbb': 222}, {'ccc': 333}]# ['aaa', 'bbb', 'ccc']
1 0
原创粉丝点击