当前位置:网站首页>len()的使用
len()的使用
2022-08-09 14:20:00 【青蛙爱游泳】
函数:len()
1:作用:返回字符串、列表、字典、元组等长度
2:语法:len(str)
3:参数:str:要计算的字符串、列表、字典、元组等
4:返回值:字符串、列表、字典、元组等元素的长度
5:实例
5.1、计算字符串的长度:
>>> s = "hello good boy doiido"
>>> len(s)
21
5.2、计算列表的元素个数:
>>> l = ['h','e','l','l','o']
>>> len(l)
5
5.3、计算字典的总长度(即键值对总数):
>>> d = {
'num':123,'name':"doiido"}
>>> len(d)
2
5.4、计算元组元素个数:
>>> t = ('G','o','o','d')
>>> len(t)
4
6、别例:
>>>import random
>>>a=[random.randint(1,100) for i in range(10)] #随机生成10个范围为1到100的数
>>>a
[72,26,80,65,34,86,19,74,52,40]
>>>print(max(a),min(a),sum(a)) #函数调用
86 19 548
>>> max(['aa','b'],key=len) #长度最大的字符串,key参数的值应为可调用对象
'aa'
#如果需要计算该列表中所有元素的平均值,可以使用下面的方法:
>>>sum(a)/len(a)
54.8
版权声明:本文为CSDN博主「xueli1991」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/xueli1991/article/details/52277084
边栏推荐
猜你喜欢

【DevOps】jekinsBuild step ‘Execute shell‘ marked build as failure

Refuse to "reinvent the wheel", Baidu EasyDL lets you play with AI custom development

leetcode 剑指 Offer 07. 重建二叉树

ELK deployment

SwiftUI 导航教程之如何实现没有 Navigation View的 SwiftUI 导航功能

Assembly language learning (4)

RHCE课程总结

How to adjust the spacing between numbers and text in Word?

Simulate the realization of strcpy function (including multiple optimization ideas)

YOLOv5网络详解
随机推荐
Minesweeper game
概率论基础知识整理 | 随机变量
概率论基础知识整理 | 随机变量的数字特征
Architect's learning experience summary
SwiftUI 导航教程之如何实现没有 Navigation View的 SwiftUI 导航功能
my creative day
Assembly language learning (4)
#25-1 OJ 78 Calculate birthday day of the week
spacedesk-notebook, tablet, extended screen-solve the problem that the tablet font is too small
数据建模已死,真的吗?
冰冰学习笔记:new与delete
Several common registries and their differences
ELK deployment
递归实现汉诺塔问题
simulink仿真pid控制伺服系统
RHCE课程总结
RHCE Course Summary
apt-get install 和pip install 的区别
论文笔记CIRS
看完腾讯大佬90天整理的“Redis深度笔记”,我直接当场膜拜