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]

好了,本节就到这了

猜你喜欢

转载自blog.csdn.net/geek_xiong/article/details/82219754