Python3之序列相关的函数---len、max、min、sum、any、all以及reversed

序列相关的函数:

len(L) 返回序列的长度
max(L) 返回序列中的最大值
min(L) 返回序列中的最小值
sum(L) 返回序列的元素的和(只有数字型才可以)
any(L) 返回布尔值,序列中有一个为真就返回True,都为假的时候才返回False
all(L) 返回布尔值,序列中全部为真时返回True,只要有一个假就返回False

举个栗子:

>>> L = [1,2,3,4,5,6]
>>> len(L)
6
>>> max(L)
6
>>> min(L)
1
>>> sum(L)
21
>>> any(L)
True
>>> all(L)
True
>>> 

这个栗子比较简单,有的看不出来,下边针对几个单独拿出来比较:

>>> L = ['hh','sfsf',4,True, False]
>>> max(L)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    max(L)
TypeError: '>' not supported between instances of 'int' and 'str'

以上这个栗子告诉我们数字型的和字符型的无法比较

>>> L = ['hh','sfsf',4,True, False]
>>> sum(L)
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    sum(L)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

以上这个栗子告诉我们数字型的和字符型的无法进行加运算

>>> L = ['hh','sfsf',4,True, False]
>>> any(L)
True

以上这个栗子只有一个False是假,其他的都是真,所以是返回True

>>> L = ['hh','sfsf',4,True, False]
>>> all(L)
False

以上这个栗子有一个False是假,就算其他的都是真,也会返回False

>>> L = ['hh','sfsf','er']
>>> max(L)
'sfsf'
>>> min(L)
'er'
>>> sum(L)
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    sum(L)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 

以上这个栗子就是为了验证sum求和,答案很明显了,字符串是无法求和运算的。


reversed(x) 返回反向顺序的可迭代对象

reversed(x) 不能直接使用,可以在for中使用
举个栗子:

s = 'ABC'
for x in s:
    print(x)  # A B C
for x in reversed(s):
    print(x)  # C B A

L = [1,3,5,7,9]
L2 = [x ** 2 for x in reversed(L)]  # [81, 49, 25, 9, 1]

好了,本节就到这了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秒不可闫M先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值