DataWhale7月学习——Python入门

Task 4:列表、元组和字符串

本节我们初步学习Python中列表、元祖和字符串的基本知识。文章给出了一些重点知识的.py程序便于读者深入理解。本文的程序编写基于Python3.0+,安装环境使用的是PyCharm。

列表

Python中的容器数据类型有:列表<class ‘list’>、元组<class ‘tuple’>、字典<class ‘dict’>、
集合<class ‘set’>、字符串<class ‘str’>
列表不像元组,列表内容可以更改,因此一些操作如:append、 extend、insert、remove都可以用在列表上

列表的定义与创建

列表是有序集合、没有固定大小,能够保存任意数量类型的Python对象
[元素1, 元素2, …, 元素n ]
下面我们创建一个普通列表

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x, type(x))
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] <class 'list'>
x = [2, 3, 4, 5, 6, 7]
print(x, type(x))
# [2, 3, 4, 5, 6, 7] <class 'list'>
1234567

我们也可以用range()函数创建列表

x = list(range(10))
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
x = list(range(1, 11, 2))
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>
x = list(range(10, 1, -2))
print(x, type(x))
# [10, 8, 6, 4, 2] <class 'list'>

同样可以利用推导式创建列表

x = [0] * 5
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>
x = [0 for i in range(5)]
print(x, type(x))
# [0, 0, 0, 0, 0] <class 'list'>
x = [i for i in range(10)]
print(x, type(x))
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <class 'list'>
x = [i for i in range(1, 10, 2)]
print(x, type(x))
# [1, 3, 5, 7, 9] <class 'list'>

利用列表可以创建一个二维数组

x = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]]
print(x, type(x))
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [0, 0, 0]] <class 'list'>
for i in x:
 print(i, type(i))
# [1, 2, 3] <class 'list'>
# [4, 5, 6] <class 'list'>
# [7, 8, 9] <class 'list'>
# [0, 0, 0] <class 'list'>
x = [[0 for col in range(3)] for row in range(4)]
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x = [[0] * 3 for row in range(4)]
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>

列表中保存的是对象的指针,即使保存一个简单的[1,2,3],也有3个指针和3个整数对象
注:x = [a] * 4 只是创建4个指向list的引用,所以一旦a改变,x中4个a也会随之改变,如:

x = [[0] * 3] * 4
print(x, type(x))
# [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] <class 'list'>
x[0][0] = 1
print(x, type(x))
# [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]] <class 'list'>

创建一个混合列表

mix = [1, 'lsgo', 3.14, [1, 2, 3]]
print(mix) # [1, 'lsgo', 3.14, [1, 2, 3]]

创建一个空列表

empty = []
print(empty) # []

列表中的元素操作

向列表中添加元素

append、extend、insert可对列表增加元素,没有返回值,都是直接修改原数据对象
1.list.append(obj) 在列表末尾添加新的对象,只接受一个参数,被追加的元素在list中保持着原结构类型

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] 
x.append(['Thursday', 'Sunday'])
print(x) 
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', ['Thursday', 'Sunday']]
print(len(x)) # 6

2.list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(可以理解为扩展,即把一个东西里的所有元素添加到列表后)

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] 
x.extend(['Thursday', 'Sunday'])
print(x) 
# ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Thursday', 'Sunday']
print(len(x)) # 7

3.list.insert(index, obj) 在编号index位置前插入obj

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] 
x.insert(2, 'Sunday')
print(x)
# ['Monday', 'Tuesday', 'Sunday', 'Wednesday', 'Thursday', 'Friday']
print(len(x)) # 6
删除列表中的元素

1.list.remove(obj) 移除列表中某个值的第一个匹配项(指定具体要删除的元素)

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] 
x.remove('Monday')
print(x) # ['Tuesday', 'Wednesday', 'Thursday', 'Friday']

2.list.pop([index=-1]) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
(指定一个索引)

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'] 
y = x.pop()
print(y) # Friday
y = x.pop(0)
print(y) # Monday
y = x.pop(-2)
print(y) # Wednesday

3.del var1[, var2 ……] 删除单个或多个对象

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
del x[0:2]
print(x) # ['Wednesday', 'Thursday', 'Friday']
获取列表中的元素

通过元素的索引值,从列表中获取单个元素(列表索引值是从0开始);
通过索引指定为-1(-2),Python返回最后一个(倒数第二个)列表元素

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x[0], type(x[0])) # Monday <class 'str'>
print(x[-1], type(x[-1])) # Friday <class 'str'>
print(x[-2], type(x[-2])) # Thursday <class 'str'>

注意切片(start : stop : step)在列表中的引用方式

x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(x[3:]) # ['Thursday', 'Friday']
print(x[-3:]) # ['Wednesday', 'Thursday', 'Friday']

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[:3]) # ['Monday', 'Tuesday', 'Wednesday']
print(week[:-3]) # ['Monday', 'Tuesday']

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:3]) # ['Tuesday', 'Wednesday']
print(week[-3:-1]) # ['Wednesday', 'Thursday']

week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(week[1:4:2]) 
# ['Tuesday', 'Thursday']
print(week[:4:2]) 
# ['Monday', 'Wednesday']
print(week[1::2]) 
# ['Tuesday', 'Thursday']
print(week[::-1]) 
# ['Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday']
列表的拷贝
list1 = [123, 456, 789, 213]
list2 = list1
list3 = list1[:]
print(list2) # [123, 456, 789, 213]
print(list3) # [123, 456, 789, 213]
list1.sort()
print(list2) # [123, 213, 456, 789]
print(list3) # [123, 456, 789, 213]

list1 = [[123, 456], [789, 213]]
list2 = list1
list3 = list1[:]
print(list2) # [[123, 456], [789, 213]]
print(list3) # [[123, 456], [789, 213]]
list1[0][0] = 111
print(list2) # [[111, 456], [789, 213]]
print(list3) # [[111, 456], [789, 213]]

列表中的常用操作符

等号 == 只有成员和成员位置都相同时才返回True
列表和元组一样,拼接有两种方式(加号+ 首位拼接、乘号*复制拼接)

list1 = [123, 456]
list2 = [456, 123]
list3 = [123, 456]
print(list1 == list2) # False
print(list1 == list3) # True
list4 = list1 + list2 # extend()
print(list4) # [123, 456, 456, 123]
list5 = list3 * 3
print(list5) # [123, 456, 123, 456, 123, 456]
list3 *= 3
print(list3) # [123, 456, 123, 456, 123, 456]
print(123 in list3) # True
print(456 not in list3) # False

列表的其他方法

1.统计某个元素在列表中出现的位置 list.count(obj)

list1 = [123, 456] * 3
print(list1) # [123, 456, 123, 456, 123, 456]
num = list1.count(123)
print(num) # 3

2.从列表中找出某个值第一个匹配项的索引位置 list.index(x, start, end)

list1 = [123, 456] * 5
print(list1.index(123)) # 0
print(list1.index(123, 1)) # 2
print(list1.index(123, 3, 7)) # 4

3.反向列表中的元素 list.reverse()

x = [123, 456, 789] 
x.reverse()
print(x) # [789, 456, 123]

4.对原列表进行排序 list.sort(key=None, reverse=False)
key:用来进行比较的元素,只有一个参数、具体的函数的参数就是取自可迭代对象中、指定可迭代对象的一个元素进行排序
reverse:排序规则(reverse=False 升序(默认值)、reverse=True 降序)
没有返回值,会对列表的对象进行排序

x = [123, 456, 789, 213] x.sort()
print(x)
# [123, 213, 456, 789]

x.sort(reverse=True)
print(x)
# [789, 456, 213, 123]

# 获取列表的第⼆个元素
def takeSecond(elem):
    return elem[1]
x = [(2, 2), (3, 4), (4, 1), (1, 3)]
x.sort(key=takeSecond)
print(x)

x.sort(key=lambda a: a[0])
print(x)
# [(1, 3), (2, 2), (3, 4), (4, 1)]

元组

元祖的语法结构为:(元素1, 元素2, …, 元素n)

创建和访问元组

Python的元组和列表类似,不同之处在于tuple被创建之后不能对其修改,类似字符串;元组使用小括号,列表使用方括号
创建元组可以用(),也可以什么也不用;
注意:当元组中只包含一个元素时,需要在元素后面加逗号,否则括号会被当作运算符使用

t1 = (1, 10.31, 'python')
t2 = 1, 10.31, 'python'
print(t1, type(t1))
# (1, 10.31, 'python') <class 'tuple'>
print(t2, type(t2))
# (1, 10.31, 'python') <class 'tuple'>
tuple1 = (1, 2, 3, 4, 5, 6, 7, 8)
print(tuple1[1]) # 2
print(tuple1[5:]) # (6, 7, 8)
print(tuple1[:5]) # (1, 2, 3, 4, 5)
tuple2 = tuple1[:]
print(tuple2) # (1, 2, 3, 4, 5, 6, 7, 8)

temp = (1)
print(type(temp)) # <class 'int'>
temp = 2, 3, 4, 5
print(type(temp)) # <class 'tuple'>
temp = []
print(type(temp)) # <class 'list'>
temp = ()
print(type(temp)) # <class 'tuple'>
temp = (1,)
print(type(temp)) # <class 'tuple'>

print(8 * (8)) # 64
print(8 * (8,)) # (8, 8, 8, 8, 8, 8, 8, 8)

元组也可以用来创建二维数组

nested = (1, 10.31, 'python'), ('data', 11)
print(nested)
# ((1, 10.31, 'python'), ('data', 11))

元组中可以用整数来对其进行索引和切片

#索引
print(nested[0])
# (1, 10.31, 'python')
print(nested[0][0], nested[0][1], nested[0][2])
# 1 10.31 python

#切片
print(nested[0][0:2])
# (1, 10.31)

更新和删除一个元组

元组有不可更改的性质,因此不能直接给元组赋值,但是只要元组中的元素可更改,那么我们可以直接更改其元素

week = ('Monday', 'Tuesday', 'Thursday', 'Friday')
week = week[:2] + ('Wednesday',) + week[2:]
print(week) # ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday')

t1 = (1, 2, 3, [4, 5, 6])
print(t1) # (1, 2, 3, [4, 5, 6])
t1[3][0] = 9
print(t1) # (1, 2, 3, [9, 5, 6])

元组相关的操作符

拼接

元组拼接有两种方式,即用+(首位拼接)、*(复制拼接)

t1 = (2, 3, 4, 5)
t2 = ('⽼马的程序⼈⽣', '⼩马的程序⼈⽣')
t3 = t1 + t2
print(t3) 
# (2, 3, 4, 5, '⽼马的程序⼈⽣', '⼩马的程序⼈⽣')
t4 = t2 * 2
print(t4) 
# ('⽼马的程序⼈⽣', '⼩马的程序⼈⽣', '⽼马的程序⼈⽣', '⼩马的程序⼈⽣')
内置

t.count(‘x’):记录x在元组t中出现的次数
t.index(x):找到元素在元组t的索引

t = (1, 10.31, 'python')
print(t.count('python')) # 1
print(t.index(10.31)) # 1
解压

解压一维数组(有几个元素左边括号定义几个变量)

t = (1, 10.31, 'python') 
(a, b, c) = t
print(a, b, c)
# 1 10.31 python

解压二维元组(按照元组里的元祖结构定义变量)

t = (1, 10.31, ('OK', 'python'))
(a, b, (c, d)) = t
print(a, b, c, d)
# 1 10.31 OK python

想取元组中的几个元素,用通配符*

t = 1, 2, 3, 4, 5 
a, b, *rest, c = t
print(a, b, c) # 1 2 5
print(rest) # [3, 4]

a, b, *_ = t
print(a, b) # 1 2

字符串

字符串定义

Python中字符串被定义为成对的单引号或双引号之间的字符集合

t1 = 'i love Python!'
print(t1, type(t1))
# i love Python! <class 'str'>
t2 = "I love Python!"
print(t2, type(t2))
# I love Python! <class 'str'>
print(5 + 8) # 13
print('5' + '8') # 58

如果字符串中需要单引号或双引号,可以使用转义符号\对字符串中的符号进行转义

print('let\'s go') # let's go
print("let's go") # let's go

原始字符串只需要再字符串前加一个英文字母r即可

print(r'C:\Program Files\Intel\Wifi\Help') 
# C:\Program Files\Intel\Wifi\Help

Python三引号允许一个字符串跨多行,字符串可以包含换行符、制表符及其他特殊字符

para_str = """这是⼀个多⾏字符串的实例
多⾏字符串可以使⽤制表符
TAB ( \t )。
也可以使⽤换⾏符 [ \n ]。
"""
print (para_str)
'''
这是⼀个多⾏字符串的实例
多⾏字符串可以使⽤制表符
TAB ( )。
也可以使⽤换⾏符 [
 ]。
'''

切片与拼接

切片通常写成start:end形式(包括start但不包括end)
索引值可正可负,正索引从0开始,从左往右;负索引值从-1开始,从右往左。使用负数索引时,会从最后一个元素开始计数(最后一个元素的索引是-1)

str1 = 'I Love LsgoGroup'
print(str1[:6]) # I Love
print(str1[5]) # e
print(str1[:6] + " 插⼊的字符串 " + str1[6:]) 
# I Love 插⼊的字符串 LsgoGroup
s = 'Python'
print(s) # Python
print(s[2:4]) # th
print(s[-5:-2]) # yth
print(s[2]) # t
print(s[-1]) # n

常用的内置方法

capitalize()将字符串的第一个字符转化为大写
lower()转换字符串中的所有大写字符为小写
upper()转换字符串中的小写字符为大写
swapcase()转化字符串中的大写字母为小写,小写字母为大写

str2 = 'xiaoxie'
print(str2.capitalize()) # Xiaoxie

str2 = "DAXIExiaoxie"
print(str2.lower()) # daxiexiaoxie
print(str2.upper()) # DAXIEXIAOXIE
print(str2.swapcase()) # daxieXIAOXIE

count(str, beg= 0,end=len(string))返回str在string里面出现的次数,如果beg或者end指定则返回指定范围内str出现的次数
endswith(suffix, beg=0, end=len(string))检查字符串是否以指定子字符串suffix结束,如果是,返回True,否则返回False。如果beg和end指定值,则在指定范围内检查
startswith(substr, beg=0,end=len(string))检查字符串是否以指定子字符串substr开头,如果是,返回True,否则返回False。如果beg和end指定值,则在指定范围内检查

str2 = "DAXIExiaoxie"
print(str2.count('xi')) # 2

str2 = "DAXIExiaoxie"
print(str2.endswith('ie')) # True
print(str2.endswith('xi')) # False
print(str2.startswith('Da')) # False
print(str2.startswith('DA')) # True

find(str, beg=0, end=len(string))检测str是否包含在字符串中,如果指定范围beg和end,则检查是否包含在指定范围内,如果包含,返回开始的索引值,否则返回-1
rfind(str, beg=0,end=len(string))类似于find(),只是从右开始查找

str2 = "DAXIExiaoxie"
print(str2.find('xi')) # 5
print(str2.find('ix')) # -1
print(str2.rfind('xi')) # 9

isnumeric()如果字符串只包含数字字符,则返回True,否则返回False

str3 = '12345'
print(str3.isnumeric()) # True
str3 += 'a'
print(str3.isnumeric()) # False

ljust(width[, fillchar])返回一个原字符串左对齐,并使用fillchar填充至长度width的新字符串
rjust(width[, fillchar])返回一个原字符串右对齐,并使用fillchar填充至长度width的新字符串

str4 = '1101'
print(str4.ljust(8, '0')) # 11010000
print(str4.rjust(8, '0')) # 00001101

lstrip([chars])截掉字符串左边的空格或者指定字符
rstrip([chars])删除字符串末尾的空格或指定字符
strip([chars])在字符串上执行lstrip()和rstrip()

str5 = ' I Love LsgoGroup '
print(str5.lstrip()) # 'I Love LsgoGroup '
print(str5.lstrip().strip('I')) # ' Love LsgoGroup '
print(str5.rstrip()) # ' I Love LsgoGroup'
print(str5.strip()) # 'I Love LsgoGroup'
print(str5.strip().strip('p')) # 'I Love LsgoGrou'

partition(sub)找到子字符串sub,把字符串分为一个三元组(pre_sub,sub,fol_sub),如果字符串中不包含sub则返回(‘原字符串’,’’,’’)
rpartition(sub)类似partition()方法,不过是从右边开始查找

str5 = ' I Love LsgoGroup '
print(str5.strip().partition('o')) # ('I L', 'o', 've LsgoGroup')
print(str5.strip().partition('m')) # ('I Love LsgoGroup', '', '')
print(str5.strip().rpartition('o')) # ('I Love LsgoGr', 'o', 'up')

replace(old, new [, max])把字符串中的old替换成new,如果max指定,则替换不出超过max次

str5 = ' I Love LsgoGroup '
print(str5.strip().replace('I', 'We')) # We Love LsgoGroup

split(str="", num),不带参数默认是以空格为分隔符切片字符串,如果num参数由设置,则近分割num个子字符串,返回切片后的子字符串拼接的列表

str5 = ' I Love LsgoGroup '
print(str5.strip().split()) # ['I', 'Love', 'LsgoGroup']
print(str5.strip().split('o')) # ['I L', 've Lsg', 'Gr', 'up']

u = "www.baidu.com.cn"
# 使⽤默认分隔符
print(u.split()) # ['www.baidu.com.cn']
# 以"."为分隔符
print((u.split('.'))) # ['www', 'baidu', 'com', 'cn']
# 分割0次
print((u.split(".", 0))) # ['www.baidu.com.cn']
# 分割⼀次
print((u.split(".", 1))) # ['www', 'baidu.com.cn']
# 分割两次
print(u.split(".", 2)) # ['www', 'baidu', 'com.cn']
# 分割两次,并取序列为1的项
print((u.split(".", 2)[1])) # baidu
# 分割两次,并把分割后的三个部分保存到三个变量
u1, u2, u3 = u.split(".", 2)
print(u1) # www
print(u2) # baidu
print(u3) # com.cn

string = "hello boy<[www.baidu.com]>byebye"
print(string.split('[')[1].split(']')[0]) # www.baidu.com
print(string.split('[')[1].split(']')[0].split('.')) # ['www', 'baidu', 'com']

splitlines([keepends])按照(’\r’,’\r\n’,’\n’)分隔,返回一个包含各行作为元素的列表,如果参数keepends为False,不包含换行符,如果为True,则保留换行符

str6 = 'I \n Love \n LsgoGroup'
print(str6.splitlines()) # ['I ', ' Love ', ' LsgoGroup']
print(str6.splitlines(True)) # ['I \n', ' Love \n', ' LsgoGroup']

maketrans(intab, outtab)创建字符映射的转换表,第一个参数为字符串,表示需要转换的字符,第二个参数为字符串表示转化的目标
translate(table, deletechars="")根据参数table给出的表,转换字符串的字符,要过滤掉的字符放到
deletechars参数中

str = 'this is string example....wow!!!'
intab = 'aeiou'
outtab = '12345'
trantab = str.maketrans(intab, outtab)
print(trantab) # {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}
print(str.translate(trantab)) # th3s 3s str3ng 2x1mpl2....w4w!!!

字符串格式化:format函数

str = "{0} Love {1}".format('I', 'Lsgogroup') # 位置参数
print(str) # I Love Lsgogroup
str = "{a} Love {b}".format(a='I', b='Lsgogroup') # 关键字参数
print(str) # I Love Lsgogroup
str = '{0:.2f}{1}'.format(27.658, 'GB') # 保留⼩数点后两位
print(str) # 27.66GB

练习题

1.列表操作练习题

lst1=[2,5,6,7,8,9,2,9,9]
lst1.append(15)
print(lst1)

lst2=[2,5,6,7,8,9,2,9,9]
lst2.insert(math.ceil(len(lst2)/2),20)
print(lst2)

lst3=[2,5,6,7,8,9,2,9,9]
lst3.extend([2,5,6])
print(lst3)

lst4=[2,5,6,7,8,9,2,9,9]
index_to_delete = [5, 7, 8] # 需要同时删除的索引位置
lst42 = [lst4[i] for i in range(0, len(lst4), 1) if i not in index_to_delete]
print(lst42)

lst5=[2,5,6,7,8,9,2,9,9]
lst5.reverse()
print(lst5)

lst6=[2,5,6,7,8,9,2,9,9]
lst6.sort()  #从小到大
print(lst6)
lst7=[2,5,6,7,8,9,2,9,9]
lst7.sort(reverse=True)  #从大到小
print(lst7)

2.修改列表

lst=[1,[4,6],True]
lst[0]=lst[0]*2
lst[1]=[2*i for i in lst[1]]
print(lst)

3.leetcode 852:山脉数组的峰顶索引

class Solution:
  def peakIndexInMountainArray(self, A: List[int]) -> int:
      mid = 0 # 记录山脉的顶点
      len = A.length # 数组长度
      #山脉的条件1:A.length >= 3
      if len < 3:
        return(False)
      # 山脉的顶点不能在第一个
     # 山脉的条件2: A[0] < A[1] < ... A[i - 1] < A[i]
      if A[0] > A[1]:
         return(False)

      #找出顶点的位置:
      for i in range(len-1) :
          if A[i] > A[i + 1]:
              mid = i
          break
              
      # 山脉的条件3: A[i] > A[i + 1] > ... > A[B.length - 1]
      for j in range(mid,len-1):
         if A[j] <= A[j + 1]:
          return(False)
       # 所有条件都满足了
      return(True)

results = Solution()
results.peakIndexInMountainArray([1, 3, 4, 5, 3])

1.元组概念

(1, 2)*2 
# (1, 2, 1, 2) <class 'tuple'>
(1, )*2 
# (1, 1) <class 'tuple'>
(1)*2
# 2 <class 'int'>

2.拆包
(1)拆包:对于函数中的多个返回数据,去掉元组,列表或者字典直接获取里面数据的过程
(2)以下是一个拆包过程

a, b = 1, 2

(3)可迭代对象拆包时,可以利用python中的*操作符拆包和赋值可迭代对象

t=(20,8)  # t是一个元组
divmod(*t)  # *t是对元组进行拆包,传参的时候我们希望传两个单元素进去,而不是一个元组
(2, 4)
print(*t)  # 拆包之后的输出  
20 8

1.实现isdigit函数,判断字符串里是否只包含数字0-9

def isdigit(string):
    for i in string
        if is.numeric(i)==True and i>=0 and i<=9:
            print(True)
        else:
           print(False)
print("123".isdigit())	

2.leetcode 5题:最长回文子串

class Solution:
   def longestPalindrome(self, s: str) -> str:
       temp, max_p, 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[l+1:r] if l == -1 or r == length else s[l+1:r]   # 因为不同的边界条件返回的子串索引取值是有规律的!

           temp = compare(index_left, index_right)  # 判断形式1是否存在
           max_p = temp if len(temp) > len(max_p) else max_p  # 判断是否比当前的回文字符串更长

           try:s[index+1]
           except:continue

           if s[index] == s[index+1]:  # 判断形式2是否存在
               left, right = index, index + 1
               temp = compare(left, right)  # 扩散
               max_p = temp if len(temp) > len(max_p) else max_p   # 判断是否比当前的回文字符串更长
       print(max_p)  # 返回最长回文字符串

results = Solution()
results.longestPalindrome("cbbbd")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值