python数据结构list,string,tuple,set,dictionary常用操作
1.列表list[]

上述的list.index(item),与string.find(item)类似,find还可以加参数,从指定位置查找返回索引,find(item,start)
-
list与range快速生成list的方法:
lst=list(range(10)) #lst=[0,1,2,3,4,5,6,7,8,9]
list(range(5,10)) #[5,6,7,8,9]
list(range(5,10,2)) #[5,7,9]
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)) #向其中添加指定范围元素
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中元素顺序排列,注意:没有重复的元素
from itertools import combinations
for comb in combinations([1,2,3],2)
print(comb)
结果
(1,2)
(1,3)
(2,3)
2-字符串string:

与list不同的是,字符串内容不可改变
nm='Bob'
nm[0] #'B'
nm[0]='C' # error,不支持赋值
Traceback (most recent call last):
File "", line 1, in
TypeError: 'str' object does not support item assignment
-
sr.replace(old,new,times)
sr='abcdefg'
sr.replace('d','8') #sr='abc8efg',将字符串中的字符'd'全部 全部替换成字符'8',
#第三个参数表示替换指定次数
sr='abddfdg'
sr.replace('d','8',2) #'ab88fdg' 指定替换2次
-
sr.index(tiem)
str1='abcdcef'
str1.index('c') #2,只会返回首个匹配的元素索引
3-元组tuple():
元组的操作与list操作类似,同样地,元组的内容也是不能改变,如果需要改变元组的内容,可以将元组(tuple)改变为列表(list),值修改后再改变回元组即可
4-集合set():

对于去掉重复的元素,直接set(mylist)取到结果,
集合,无序,无重复元素
定义一个集合{}表示:
oneset={1,2,3,4}
由于set无序,pop()的结果具有不确定性
5-字典{}

无序的键(key)值(value)对,逗号分割每个键值对
info={'name':'Bob','add':'backstreet','code':'101010'}
info['name'] #'Bob'
infolst=list(info.items()) #[('name', 'Bob'), ('add', 'backstreet'), ('code', '101010')],转成列表,键-值-->元组,元素
infolst[0] #('name','Bob')
infolst[0][1] #'Bob'

浙公网安备 33010602011771号