列表
python列表不同C++数组,由于python变量没有固定数据类型,列表可以任何东西
n = [1, 'fin', 2, [3,"r54"]]
m = []
m.append(1) #添加元素
m.extend(n) #列表中添加其他列表
m.insert(0, 0) #插入元素,输入为id & 插入元素
m[1], m[2] = m[2], m[1] #swap两个下标的元素
m.remove(1) #删除元素1,没有时会报错
del m[1] #删除下标1的元素
m.pop() #出栈,返回列表出栈值
m[1:3] #分片,返回一个列表的拷贝,这里的拷贝不会随着m而更改
m[::-1] #反转列表 m.reverse()
列表成员
>>>dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
常用的有
m = [1, 1, 1, 5, 8, 12, 4, 3, 3]
m.count(1) #返回1出现了几次
m.index(1) #返回第一个1的下标
m.sort() #排序,sort(key=None, reverse=False)
#注意
list1 = [1,2,3]
list2 = list1
list1[2] = 5
print(list1)
print(list2) #list2随着list1也更改了
元组
元组和列表的最大区别在于:元组不可改变,列表可以任意进行修改
tuple1 = (1, 2, 3, 4, 5) #创建元组
tuple2 = tuple1[1:3]
tuple3 = 1, 2, 3
tuple4 = 1,
字符串
先来看字符串的方法
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
查找使用说明
help(str.find) #看find的使用说明
常用方法
str1 = "I'm not alone"
str2 = str1.casefold() #全置为小写
str2.find("not") #查找 not 子串,返回位置
' '.join(["I'm","not","alone"]) #字符串拼接
str3 = str2.replace("not", "realy") #替换字段
list1 = str1.split(" ") #拆分字符串
格式化
"{0} am {1}".format("I", "alone")
除了使用format形式进行格式化外,还可以使用 格式化操作符 %,例如
'%c' % 97 #字符转换
"%c%d" % (97,123)
'%5.3f' % 27.5678 #符点数控制
'%#X' % 100 #十六进制转换
内建方法
类型转换
list(iterable)
tuple(iterable)
str(obj)
返回长度
len(sub)
取最值
max(...)
min(...)
生成二元组
enumerate(iterable)
for each in enumerate(iterable):
...
zip() 返回各个可迭代参数的共同组成的元组