从列表中找出最长的字符串,有两种方式,一种用for循环比较,另一种是python的max方法。
使用的txt文件格式:
方法一、 使用for循环代码:
def get_longest_name():
school = []
max_length = 0
longest_strings = []
with open('school.txt',encoding='utf-8') as f:
content = f.readlines()
for i in content:
school.append(i.strip("\n"))
if len(i) > max_length:
max_length = len(i)
#strip()首尾空格
longest_string = i.strip()
#从所有数据中随机抽取10个
schools = random.sample(school,10)
print(school)
print("\033[1;37;44m 最长的学校的名字:{} \033[0m".format(longest_string))
print(schools)
运行结果如下:
方法二、max()
schools1 = ['阜阳师范大学', '集美大学', '齐齐哈尔医学院', '青海大学', '黑龙江财经学院', '金陵科技学院', '陕西国际商贸学院', '马鞍山职业技术学院', '黑龙江工程学院昆仑旅游学院', '黑龙江省市中国人民公安大学']
print(max(schools1,key=len,default='hello world'))
key:指定取最大值的函数,我们要取长度最大的,故设置为len
default:如果取不到默认返回的值,这里设置为”hello world“,即为列表中不存在任何元素时返回”“hello world”。
另外,在schools中最长的元素不仅仅是第一次找到的元素,后续如果有同样的元素是没有返回的。如上图返回结果:
如果要找到所有的最长的字符串,需要再找一次
schools1 = ['阜阳师范大学', '集美大学', '齐齐哈尔医学院', '青海大学', '黑龙江财经学院', '金陵科技学院', '陕西国际商贸学院', '马鞍山职业技术学院', '黑龙江工程学院昆仑旅游学院', '黑龙江省市中国人民公安大学']
print(max(schools1,key=len,default='hello world'))
#找出字符串中所有最长的字符串
max_length2 = len(max(schools1,key=len))
longest_strings1 = []
for i in schools1:
if len(i) == max_length2:
longest_strings1.append(i)
print("\033[1;33;40m 所有最长学校的名字列表:{} \033[0m".format(longest_strings1))
运行结果:
希望帮到大家~ 喜欢的点赞哦~❤️❤️❤️❤️❤️❤️❤️❤️❤️
如果有更好的方法欢迎留言评论吧~❤️❤️❤️❤️❤️❤️❤️❤️❤️