练习题:
列表:
1.
x=[‘2’,‘5’,‘6’,‘7’,‘8’,‘9’,‘2’,‘9’,‘9’]
x.append(‘15’)
print(x)
[‘2’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘2’, ‘9’, ‘9’, ‘15’]
x=[‘2’,‘5’,‘6’,‘7’,‘8’,‘9’,‘2’,‘9’,‘9’]
x.insert(5,‘20’)
print(x)
[‘2’, ‘5’, ‘6’, ‘7’, ‘8’, ‘20’, ‘9’, ‘2’, ‘9’, ‘9’]
x=[‘2’,‘5’,‘6’,‘7’,‘8’,‘9’,‘2’,‘9’,‘9’]
x.extend([‘2’,‘5’,‘6’])#此处要注意区分
print(x)
[‘2’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘2’, ‘9’, ‘9’, ‘2’, ‘5’, ‘6’]
x=[‘2’,‘5’,‘6’,‘7’,‘8’,‘9’,‘2’,‘9’,‘9’]
y=x.pop(3)
print(y)
7
x=[‘2’,‘5’,‘6’,‘7’,‘8’,‘9’,‘2’,‘9’,‘9’]
x.reverse()
print(x)
[‘9’, ‘9’, ‘2’, ‘9’, ‘8’, ‘7’, ‘6’, ‘5’, ‘2’]
x=[‘2’,‘5’,‘6’,‘7’,‘8’,‘9’,‘2’,‘9’,‘9’]
x.sort(reverse=True)
print(x)
[‘9’, ‘9’, ‘9’, ‘8’, ‘7’, ‘6’, ‘5’, ‘2’, ‘2’]
x=[‘2’,‘5’,‘6’,‘7’,‘8’,‘9’,‘2’,‘9’,‘9’]
x.sort(reverse=False)
print(x)
[‘2’, ‘2’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘9’, ‘9’]
2.
def double_list(lst):
for index,value in enumerate(lst):
if isinstance(value,bool):
continue
if isinstance(value,(int,float)):
lst[index]*=2
if isinstance(value,list):
double_list(value)
if name==‘main’:
lst=lst=[1,[4,6],True]
double_list(lst)
print(lst)
[2, [8, 12], True]
3.
元组
结果
(1, 2, 1, 2)
(1, 1)
2
元组中只包含一个元素时,要在后面添加逗号
元组拆包就是将元组中的元素分别赋给变量。
上述过程属于拆包。
可迭代对象拆包时,
字符串
1.
*批量替换字符串中的元素,
replace(old, new [, max]) ,将字符串中的old替换成new,如果max指定,则替换不超过max次。
*将字符串按照空格进行拆分,split(str="", num) 不带参数默认是以空格为分隔符切片字符串,如果num参数有设置,则仅分隔num个子字符串,返回切片后的子字符串拼接的列表。
*去除首格空格
- strip:去掉字符串左右两边的空格
- lstrip:去掉左边的空格
- rstrip:去掉右边的空格
2.
class Solution:
def longestPalindrome(self,s:str)->str:
a,b,length="","",len(s)
for index in range(length):
index_left,index_right=index,index
def compare(l,r):
while l!=-1 and r!=length and s[l]s[r]:
l,r=l-1,r+1
return s[i+1:r] if l-1 or r==length else s[l+1:r]
a=compare(index_left,index_right)
b=a if len(a)>len(b) else b
try:s[index+1]
except:continue
if s[index]==s[index+1]:
left,right=index,index+1
a=compare(left,right)
b=a if len(a)>len(b) else b
return b