ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 常用的字符串方法 | 方法 | 说明 | |-----|-----| | capitalize() | 返回首字母的大写副本 | | find(s) | 返回字符串中首次出现参数s的索引,如果字符串中没有参数s则返回-1 | | find(s,beg) | 返回字符串中索引beg之后首次出现参数s的索引,如果字符串中索引beg之后没有参数s则返回-1 | | find(s,beg,end) | 返回字符串中索引beg与end之间首次出现参数s的索引,如果字符串中索引beg和end之间没有参数s则返回-1 | | islower() | 测试所有字符是否均为小写形式 | | isupper() | 测试所有字符是否均为大写形式 | | lower() | 将所有字符穿华为小写形式并返回 | | replace(old,new) | 将字符串中所有子串old替换为new并返回 | | split() | 将空格分隔的单词以列表的形式返回 | | split(del) | 将del分隔的子串以列表的形式返回 | | strip() | 删除字符串两端的空白符并返回 | | strip(s) | 删除字符串中的s并返回 | | upper() | 将所有字符串转化为大写形式并返回 | # 列表函数 | 函数 | 说明 | |-----|-----| | len(L) | 返回列表L中的元素数量 | | max(L) | 返回列表L中的最大值 | | min(L) | 返回列表L中的最小值 | | sum(L) | 返回列表L中所有元素的和 | # 列表方法 | 方法 | 说明 | |-----|-----| | L.append(v) | 将值v添加到列表L中 | | L.insert(i,v) | 将值v插入到列表L的索引i处,同时将其后的元素往后移以便腾出位置 | | L.remove(v) | 从列表L中移除第一次找到的值v | | L.reverse() | 反转列表L中的值的顺序 | | L.sort() | 队列表L中的值以升序排序(字符串以字母表顺序为准) | | L.pop() | 移除并返回列表L的最后一个元素(该列表不得为空) | # 集合运算及运算符 | 方法 | 运算符 | 说明 | |-----|-----|-----| | add | | 往集合中添加一个元素 | | clear | | 移除集合中的所有元素 | | difference | - | 根据一个集合中不存在于另一个集合中的元素,创建中一个新的集合 | | intersection | & | 根据两个集合中共有的元素,创建出一个新的集合 | | issubset | <= | 判断一个集合的所有元素是否都包含于另一个集合 | | issuperset | >= | 判断一个集合是否包含了另一个集合中的所有元素 | | remove | | 移除集合中的一个元素 | | symmetric_difference | ^ | 根据两个集合中所有不存在于对方的元素,创建出一个新的集合 | | union | | 根据两个集合中所有的元素,创建出一个新的集合 | # 字典 | 方法 | 说明 | |-----|-----| | clear | 清空字典内容 | | get | 返回关键字所关联的值,如果指定键不存在,则返回默认值 | | keys | 以列表的形式返回字典中的所有键。所得列表中的每个条目肯定是唯一的 | | items | 返回(key,value)列表 | | values | 以列表的形式返回字典中的所有值。所得列表中的每个条目不一定是唯一的 | | update | 用另一个字典的内容对当前字典进行更新 | 附录: ~~~ def find_two_smallest(L): '''Return a tuple of the indices of the two smallest values in list L''' if L[0] < L[1]: min1,min2 = 0,1 else: min1,min2 = 1,0 for n in range(2,len(L)): if L[n] < L[min1]: min2 = min1 min1 = n elif L[n] < L[min2]: min2 = n return (min1,min2) def linear_search(L,v): '''Return the index of the first occurrence of v in list L, or return len if v is not in L''' for i in range(len(L)): if L[i] == v: return i return len(L) def selection_sort(L): '''Reorder the values in L from smallest to largest.''' i = 0 while i != len(L): smallest = find_min(L, i) L[i],L[smallest] = L[smallest],L[i] i += 1 def find_min(L,b): '''Return the index of the smallest value in L[b:].''' smallest = b # The index of the smallest so far. i = b + 1 while i != len(L): if L[i] < L[smallest]: smallest = i i += 1 return smallest def insertion_sort(L): '''Reorder the values in L from smallest to largest.''' i = 0 while i != len(L): insert(L, i) i += 1 def insert(L, b): '''Insert L[b] where it belongs in L[0:b+1]; L[0:b-1] must already be sorted''' i = b while i != 0 and L[i-1] > L[b]: i -= 1 value = L[b] del L[b] L.insert(i, value) ~~~