Python 的内置对象

Python中一切皆是对象,主要的内置对象有:1. 数字(整型int、浮点型float)2. 字符串(不可变性) 3.列表 4.字典 5.元组(不可变性) 6.文件 7.集合(不重复性)

数字支持+-*/运算,有强大的math模块

>>> round(3.1415926,2)
3.14(保留小数点位数)

>>> num = '%.2f' %3.1414596
>>> num
'3.14'(字符串格式化,输出为字符串)

 

字符串:切片、索引、查找、替换、格式化,循环

>>> 'ming'[2] 索引
'n'
>>> 'ming'.index('n') 索引
2
>>> 'ming'.find('n')查找还可以用re模块
2
>>> 'ming'.replace('n','m')替换修改字符串的一个方法
'mimg'
>>> 'I am %s and %d years old' %('ming',18)字符串的格式化
'I am ming and 18 years old'

>>> 'ming'[::-1]
'gnim'  反转功能

列表:切片、索引、循环、追加

>>> l.append('ming') append追加至列表
>>> l
['hello', 'world', 'python', 'ming']

>>> l.extend('lily') extend是加的列表和append有区别
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y']

>>> l.extend(['hah','hey']) 追加到一个列表
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey']
>>> l.append(['nihao','hao']) 追加啥是啥
>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey', ['nihao', 'hao']] 

>>> l
['hello', 'world', 'python', 'ming', 'l', 'i', 'l', 'y', 'lily', 'hah', 'hey', ['nihao', 'hao']]
>>> l.sort()   嵌套列表不支持排序
Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
    l.sort()
TypeError: '<' not supported between instances of 'list' and 'str'
>>> l
['hah', 'hello', 'hey', 'i', 'l', 'l', 'lily', 'ming', 'python', 'world', 'y', ['nihao', 'hao']]
>>> l=['l','h','i']
>>> l.sort()
>>> l
['h', 'i', 'l']
>>> l.reverse() 取反
>>> l
['l', 'i', 'h'] 

 

字典:映射、嵌套、循环、排序

>>> dict = {'ming':'hangzhou','li':'nanjing','lucy':'shanghai'}
>>> dict['li'] 映射
'nanjing'
>>> dict['jim'] = 'shenzhne' 填充字典
>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}

>>> l = list(dict.keys()) 获取字典的键
>>> l
['ming', 'li', 'lucy', 'jim']
>>> l.sort() 排序
>>> l
['jim', 'li', 'lucy', 'ming']
>>> for each in l: 格式化输出
    print(each,dict[each])

jim shenzhne
li nanjing
lucy shanghai
ming hangzhou

>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}
>>> value = dict.get('good','moring')字典的查找get方法,没有则返回预设值而不报错
>>> value
'moring'
>>> dict
{'ming': 'hangzhou', 'li': 'nanjing', 'lucy': 'shanghai', 'jim': 'shenzhne'}
>>>

元组:一个不可变的列表

>>> T = (1,2,3,4)
>>> T.count(1)
1
>>> T.append(5) 由于不可变性,所以不能追加
Traceback (most recent call last):
  File "<pyshell#58>", line 1, in <module>
    T.append(5)
AttributeError: 'tuple' object has no attribute 'append'

集合:不重复性 支持集合运算

>>> a = {1,3,4,5}

>>> b ={1,2,4,5,6, 7}
>>> a&b交集
{1, 4, 5}
>>> a|b并集
{1, 2, 3, 4, 5, 6, 7}
>>> a-b a中有b中没有
{3}
>>> b-a b中有a中没有
{2, 6, 7}
>>> a^b ab交集中没有的
{2, 3, 6, 7}
>>>

转载于:https://www.cnblogs.com/Zhu-Xueming/p/8331092.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值