如何区分 Python序列相关的内置函数 和 序列的属性方法

如何区分 Python序列相关的内置函数 和 序列的方法

1. 在 Python 中,序列类型包括字符串、列表、元组、集合和字典,Python 序列相关的内置函数如下表。

函数功能
len()计算序列的长度,即返回序列中包含多少个元素。
max()找出序列中的最大元素。
min()找出序列中的最小元素。
list()将序列转换为列表。
str()将序列转换为字符串。
sum()计算元素和。注意,对序列使用 sum() 函数时,做加和操作的必须都是数字,不能是字符或字符串,否则该函数将抛出异常,因为解释器无法判定是要做连接操作(+ 运算符可以连接两个序列),还是做加和操作。
sorted()对元素进行排序,返回的是列表对象。内置函数sorted()不能对集合使用
reversed()反向序列中的元素。返回的是列表对象,内置函数reversed()不能对集合使用
enumerate()将序列组合为一个索引序列,多用在 for 循环中。
a = {34,54,1,2,3,56,453,4563,4}

len(a)
max(a)
min(a)
list(a)
str(a)
sum(a)
a = {34,54,1,2,3,56,453,4563,4}
# sorted(a)
# reversed(a)
for i in enumerate(a):
    print(i)


(0, 1)
(1, 34)
(2, 3)
(3, 2)
(4, 453)
(5, 4)
(6, 4563)
(7, 54)
(8, 56)

2. 集合没有sort()方法,sorted()python内置函数不能用于集合

a = {1,2,3}
a.sorted()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-29-b09d0a76cf4f> in <module>
      1 a = {1,2,3}
----> 2 a.sorted()

AttributeError: 'set' object has no attribute 'sorted'
a = {74872,42847,6,1,2,3}
a.sort()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-29-b09d0a76cf4f> in <module>
      1 a = {1,2,3}
----> 2 a.sorted()

AttributeError: 'set' object has no attribute 'sorted'

3. list的reverse()、sort()属性方法 VS 对list使用python内置函数reversed()、sort()

内置函数或方法功能使用返回值是否改变list
reverse()list的方法list.reverse()None
sort()list的方法list.sort()None
reversedpython 内置函数reversed(list)list_reverseiterator object
sortedpython内置函数sorted(list)list object
a = [84457,-332,1,2,3,-7762,73]
print(sorted(a))
print(a)
print(reversed(a))
print(a)
for i in reversed(a):
    print(i)
# 不改变原列表
[-7762, -332, 1, 2, 3, 73, 84457]
[84457, -332, 1, 2, 3, -7762, 73]
<list_reverseiterator object at 0x00000249FC6C8048>
[84457, -332, 1, 2, 3, -7762, 73]
73
-7762
3
2
1
-332
84457
a = [84457,-332,1,2,3,-7762,73]
print(a.sort())
print(a)
print(a.reverse())
print(a)
# 直接对列表原地a操作
None
[-7762, -332, 1, 2, 3, 73, 84457]
None
[84457, 73, 3, 2, 1, -332, -7762]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值