1-列表list常用的一些方法如下:

python数据结构list,string,tuple,set,dictionary常用操作

上述的list.index(item),与string.find(item)类似,find还可以加参数,从指定位置查找返回索引,find(item,start)

list与range快速生成list的方法:

1 >>>lst=list(range(10))        #lst=[0,1,2,3,4,5,6,7,8,9]
2 >>>list(range(5,10))          #[5,6,7,8,9]
3 >>>list(range(5,10,2))       #[5,7,9]
4 >>>list(range(10,1,-2))      #[10,8,6,4,2]

生成列表的其他写法:

lst=[x for x in range(5)]//lst=[0,1,2,3,4]

后面可以跟条件,例如:

lst2=[x for x in range(6) if x%2 ]//lst2=[1,3,5]

合并列表的一些方法:

rel=lst.extend(range(4)) or //向其中添加指定范围元素

rel=lst.extend([3]*5) //重复向其中添加指定元素

向有序列表插入元素:

import bisect

mylst=[1,2,3,40]

bisect.insort(mylst,2)   //mylst=[1,2,2,3,40]

切片替换,类似列表部分(切片)与另一列表连接,不过更方便

mylst=[1,2,3,4,]

mylst[:2]=["ab","bc","cd"]

//mylst=["ab","bc","cd",3,4]

列表元素的组合,还有排列permutations用法类似

combinations(iterable,r)//返回iterable中长度为r的元组组合,返回顺序按iterable中元素顺序排列,note:没有重复的元素

from  itertools import combinations

for val in combinations([1,2,3],2)

     print(val)

//结果:

(1,2)

(1,3)

(2,3)

 

2-字符串string常用的方法:

str1='Hello'

str1.replace('l','x')    //替换了所有的

str1='Hexxo'

注意这里的replace,后面还可加参数,表示替换多少次(如果查找不唯一的情况下),

str1="Hello"

str1.replace('l','x',1)

str1="Hexlo"

str1.index(item)

//只会返回首个匹配的元素索引

python数据结构list,string,tuple,set,dictionary常用操作

与list不同的是,字符串内容不可改变

>>>nm='Bob'

>>>nm[0]

>>>'B'

>>>nm[0]='C'     # error,不支持赋值

3-元组tuple:

元组的操作与list操作类似,同样地,元组的内容也是不能改变,如果需要改变元组的内容,可以将元组(tuple)改变为列表(list),值修改后再改变回元组即可

4-集合set:

对于去掉重复的元素,直接set(mylist)取到结果,

集合,无序,无重复元素

定义一个集合{}表示:

oneset={1,2,3,4}

python数据结构list,string,tuple,set,dictionary常用操作

 由于set无序,pop()的结果具有不确定性

5-字典{}

无序的键(key)值(value)对,逗号分割每个键值对

info={'name':'Bob','add':'backstreet','code':'101010'}

python数据结构list,string,tuple,set,dictionary常用操作

 

info['name']         #'Bob'

infolst=list(info.items())   #转成列表

infolst[0]   #('name','Bob')

infolst[0][1] #'Bob'

相关文章: