21ewd 发表于 2016-1-28 08:29:33

python 数据结构

list(列表)

创建list
方式1: 直接创建theList =                   ==>

方式2 : 使用内建方法list(),list方法接受一个序列参数(例如元组或者字符串)

         1 theList = list((1,2,3,4,5,6,7,8,9))   ==>
         2 theList = list("abcdefg")            ==> ["a","b","c","d","e","f","g"]

向list中增加元素
1 使用List的append方法

    theList = [] ; theList.append(1)==>

2 使用赋值的方法
    theList = [] ; theList = ==>

在List中查找指定的元素
1 使用index方法,返回的是元素在list中的序号,如元素不在list中,会抛出ValueError异常

    theList = ;indexNum = theList.index(1)   ==> indexNum - 0

2 使用 in ,如果元素存在于List 中返回True , 如果不存在返回 False
    theList=
    1 in theList ==> True
    3 in theList ==> False


删除List中指定的元素
1)使用del方法删除元素
      theList = ; del(theList)==>    


计算List的长度
1) 使用len() 方法
   theList = ; len(theList) ==> 5

map(字典)
map 每个元素包含 键(key) 和 值(value) 两部分。字典中的每个键都是唯一的

创建MAP
theMap = {"a":1,"b":2,"c":3}   ==>{ 'c': 3, 'a': 1, 'b': 2}


向MAP增加元素
向MAP增加一个关键字“a" . 关键字‘a' 对应着值1

theMap = {}
theMap["a"] = 1



在MAP中查找指定元素
检查指定的关键字是否存在于MAP中
theMap ={"a":1,"b":2,"c":3}
查找关键字'a' 是否在MAP中
'a' in theMap    ==> True

查找关键字'k'是否在MAP中
'k' in theMap   ==> False





删除MAP中制定的元素
theMap = {"a":1,"b":2,"c":3}

1 从MAP中删除指定的关键字 'b'
del(theMap['b'])   ==> {'c': 3, 'a': 1}
2 从MAP中删除关键字'm'
del(theMap['m'])   ==> KeyError: 'm'   抛出异常,不能删除不存在的关键字


计算MAP的长度

theMap = {"a":1,"b":2,"c":3}
len(theMap)==>3


String(字符串)
字符串是不可变的值


字符串的赋值
theStr = "sample line"

字符串的格式化/连接
lineOne = "one"    lineTwo = "two"

1使用 + 号连接
   lineThree = lineOne + lineTwo   ==> onetwo
2 join() 方法连接
   '-'.join() ==> onetwo
'-'.join(lineOne)                  ==>o-n-e
3 使用format方法
    1 lineThree = "%s%s"%(lineOne,lineTwo)       ==> onetwo

    2 "{0}{1}".format(lineOne,lineTwo)                   ==> onetwo

    3 "{one}{two}".format(one=lineOne , two = lineTwo)   ==> onetwo

    4p =
      "{0}{0}".format(p)                                             ==>onetwo

    5 字符串分割(splite)
       lineOne.split()                        ==> ['o','n','e']

    6 字符串去除空白字符(strip)
      "    abc    ".strip()                  ==> 'abc'


字符串的提取
      lineOne= "ne"
      lineOne[:-1] = "on"
       lineOne = "n"

       k = "abcdefg" ;k    ==> 'aceg'


字符串与其他数据类型的转换


float(str)                  float("1e-1")结果为0.1
int(str)                     int("12")      结果为12
int(str,base)             int("11",2)    结果为3,将 2进制的 11 转换为 十进制数

                              int("11",8)    结果为9 ,将8进制的 11 转换为 十进制数


字符串查找
tmp = "asdfghjkl"

1 find
    tmp.find("a")    ==> 0   #字符存在于字符串中

    find.find("z")    ==> -1#字符串不存在于字符串

2 index
    tmp.index('a')   ==> 0                   #字符存在于字符串中
    tmp.index('z')   ==>ValueError   #字符串不存在于字符串


页: [1]
查看完整版本: python 数据结构