python 基础 1.5 python数据类型(二)--列表常用方法示例

#/usr/bin/python

#coding=utf-8

#@Time   :2017/10/12 23:30

#@Auther :liuzhenchuan

#@File   :列表.py

list1 = [1,2,3,4]

print type(list1)

str1 = 'abcd'

print list(str1)

print dir(list1)

>>>

 

<type 'list'>
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

 

print '###'*20

 

#append()  在末尾追加一个元素

list2 = ['a','b','c','d']

list2.append('00')

print list2

>>> ['a', 'b', 'c', 'd', '00']

 

 

#index() 用于列表中第一个匹配项的索引位置

list3 = ['heoll','world','good','ABC']

print list3.index('good')

 

print type(str(list3))

print str(list3)

print str(list3)[20]

print (str(list3)).find('good')

 

>>> 2

 

  <type 'list'>

 

  ['heoll', 'world', 'good', 'ABC']

 

  <type 'str'>

 

  g

 

  20

 

 

 

 

#insert() 用于将制定对象插入制定位置

list4 = ['abc','tty','oop']

list4.insert(1,'aa')  //在索引1的位置后插入字符aa

print list4

 

>>> ['abc', 'aa', 'tty', 'oop']

 

 

#pop() 用于移除列表中的一个元素(默认为最后一个元素),并且返回该元素的值

print list4

 

list4.pop()

list4.pop(0)

print list4

 

>>> ['abc', 'tty', 'oop']

 

  oop

 

  abc

 

  ['tty']
 
 

#remove() 用于移除列表中某个值的第一个匹配项

list4 = ['abc','tty','oop']

list4.remove('tty')

print list4

 

>>> ['abc', 'oop']

 

 

#sort() 对列表进行原址排序,既然是原址排序,那显然元祖不可能拥有这种方法,因为元祖是不可变的

x = [4,7,8,3,5,1,2,6,9]

x.sort()

print x

 

>>> [1, 2, 3, 4, 5, 6, 7, 8, 9]

 

 

#reverse()  函数用于反向列表中的元素

x1 = ['d','c','abc','ab','a','123','1']

x1.sort()

print x1

x1.reverse()

print x1

 

>>> '1', '123', 'a', 'ab', 'abc', 'c', 'd']

 

 

#切片

x1 = ['d','c','abc','ab','a','123','1']

print x1[:]

print x1[1:]

print x1[1:5]

print x1[1:6:2]

>>> 

  ['d', 'c', 'abc', 'ab', 'a', '123', '1']

 

  ['c', 'abc', 'ab', 'a', '123', '1']

 

  ['c', 'abc', 'ab', 'a']

 

  ['c', 'ab', '123']

 

 

 

#zip()函数接受多个任意(包括0和1)序列作为参数,返回一个tuple列表。可以把多个列表叠加成一个元组列表

l1 = ['a','b','c','d']

l2 = [1,2,3,4]

l3 = zip(l1,l2)

print l3

>>> [('a', 1), ('b', 2), ('c', 3), ('d', 4)]

 

posted @ 2017-10-23 08:58  刘振川的博客  阅读(198)  评论(0编辑  收藏  举报