Task 04
——列表、元组和字符串
练习题(列表):
- 列表操作练习 →
lst = [2,5,6,7,8,9,2,9,9]
• 在列表的末尾增加元素15:
lst = [2,5,6,7,8,9,2,9,9]
lst.append(15)
#2,5,6,7,8,9,2,9,9,15
• 在列表的中间位置插入元素20:
lst = [2,5,6,7,8,9,2,9,9]
lst.insert(4,20)
#2,5,6,7,20,8,9,2,9,9
• 将列表[2,5,6]合并到lst中:
lst = [2,5,6,7,8,9,2,9,9]
lst.extend([2,5,6])
#2,5,6,7,8,9,2,9,9,2,5,6
• 移除列表中索引为3的元素:
lst = [2,5,6,7,8,9,2,9,9]
lst.pop(3)
#2,5,6,8,9,2,9,9
• 翻转列表里的所有元素:
lst = [2,5,6,7,8,9,2,9,9]
lst.reverse()
#9,9,2,9,8,7,6,5,2
• 对列表里的元素进行排序,从小到大一次从大到小一次:
lst = [2,5,6,7,8,9,2,9,9]
lst.sort(reverse=True)
#9, 9, 9, 8, 7, 6, 5, 2, 2
lst.sort(reverse=False)
#2, 2, 5, 6, 7, 8, 9, 9, 9
- 请将列表里的所有数字修改为原来的两倍→
lst = [1,[4,6],True]
:
lst = [1,[4,6],True]
#为了保证程序的普适性我选择了用函数的嵌套来完成功能
def file(x:[]):
i=0
while i<len(x):
if type(x[i])==type(1):
x[i] *= 2
elif type(x[i])==type([1,2]):
file(x[i])
i = i+1
file(lst)
print(lst)
#[2,[4,6],Ture]
- 判断是否为山顶数组:
#输入一个数组
lst=eval(input())
#判断长度
if len(lst)<3:
print('False')
exit(0)
#设置计数变量和标记变量
count=0
Mark=0
while count<len(lst)-1:
if Mark==0:
#判断上升区间的模块
if lst[count]>lst[count+1]:
#如果下降开始时count=0那么一定不是顶峰数组
if count==0:
print(False)
exit(0)
#如果不是从第一个就下降着更改标记,启用判断下降区间的模块
Mark = count
#如果从第一个一直上升到最后一个也不是顶峰数组
if Mark==0 and count==len(lst)-2:
print('False')
exit(0)
#判断下降区间的模块
if Mark != 0:
if lst[count]<lst[count+1]:
print('False')
exit(0)
count += 1
print('True')
练习题(元组):
- 元组概念:第一个元组*2后再原元组后面直接加一个一模一样的;第二个同第一个,虽然只有一个元素,但它后面因为有逗号所以被判定为元组;而第三个后面没有逗号,所以它会被判定为运算符号。
(1,2)*2==(1, 2, 1, 2)
(1,)*2==(1, 1)
(1)*2==2
- 拆包:拆包过程是将一个被封装的一个整体中的元素一一对应的拆分的对应变量的过程。如图的
a,b = 1,2
并不算是拆包过程,因为它原本就不是一个封装的整体。
可迭代对象拆包时,将占位符输入在其赋值给对应变量的位置即可。
练习题(字符串):
-
字符串函数回顾:
• 怎么批量替换字符串中的元素:用replace(old,new[,max])
把字符串中的old
替换成new
,用max
指定替换次数。
• 怎么把字符串按照空格进行拆分:用split(str" ",num)
,不带参数就是以空格分隔符切边字符串,用num
指定分隔片数。
• 怎么去除字符串的空格:可以使用替换语句吧空格的制表符替换成空。 -
实现isdigit函数:判断字符串里是否只包含数字0~9
def isdigit(string):
i=0
while i<len(string):
try:
type(int(string[i])) == type(1)
except ValueError:
print('No')
exit(0)
i += 1
print('Yes')
- 最长回文子串:
def longestPalindrome(self,s:str):
if len(s) == 1:
return s
re = s[0]
for i in range(0,len(s)-1):
for j in range(i+1,len(s)):
sta = i
end = j
flag = True
while sta < end:
if s[sta] != s[end]:
flag = False
break
sta += 1
end -= 1
if flag and j-i+1 > len(re):
re = s[i:j+1]
return re