<Python Tips> 2. 数据类型

news/2024/7/5 3:44:27

开启Python

➜  ~ docker run --rm -ti python:alpine python
Python 3.7.0 (default, Jul  4 2018, 02:26:27) 
[GCC 6.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Python对象结构

Visualize your code and get live help now

可变与不可变对象

  • 值可以改变的对象是mutable, 否则为immutable

>>> age = 18
>>> id(age)
140068432251328
>>> age
18
>>> age = 30
>>> id(age)
140068432251712
>>> age
30
>>> 
>>> class Person():
...     def __init__(self, age):
...             self.age = age
... 
>>> me = Person(age=30)
>>> me.age
30
>>> id(me)
140068426091544
>>> id(me.age)
140068432251712
>>> me.age = 18
>>> id(me)
140068426091544
>>> id(me.age)
140068432251328
>>> 

内置类型: Numbers, Strings, Sequences, Collections 与 Mapping类型

Numbers

  • Integer(整数):

>>> a = 18
>>> b = 3
>>> a + b
21
>>> a - b
15
>>> a * b
54
>>> a / b
6.0
>>> a // b
6
>>> a % b
0
>>> a ** b
5832
>>> 
  • Boolean:

>>> int(True)
1
>>> int(False)
0
>>> bool(1)
True
>>> bool(-1)
True
>>> bool(0)
False
>>> not True
False
>>> not False
True
>>> True and False
False
>>> False or True
True
>>> 1 + True
2
>>> 1 - False
1
>>> 
  • Real Number(实数) (浮点型numbers):

>>> pi = 3.1415926
>>> r = 10.5
>>> area = pi * (r ** 2)
>>> area
346.36058415
>>> 
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
>>> 
>>> 0.3 - 0.1 * 3 
-5.551115123125783e-17
>>> 
  • Complex numbers(复数):

>>> c = 3.14 + 2.73j
>>> c
(3.14+2.73j)
>>> c.real
3.14
>>> c.imag
2.73
>>> c.conjugate()
(3.14-2.73j)
>>> c * 2
(6.28+5.46j)
>>> c ** 2
(2.4067000000000007+17.1444j)
>>> d = 1 + 1j
>>> c - d
(2.14+1.73j)
>>> 
  • Fractions(分数)与decimals(小数)

>>> from fractions import Fraction
>>> Fraction(100, 48)
Fraction(25, 12)
>>> Fraction(1,3) + Fraction(2,3)
Fraction(1, 1)
>>> f = Fraction(100000, 2358)
>>> f.numerator
50000
>>> f.denominator
1179
>>> 
>>> from decimal import Decimal as D
>>> D(3.1415926)
Decimal('3.14159260000000006840537025709636509418487548828125')
>>> D('3.1415926')
Decimal('3.1415926')
>>> D(0.1) * D(3) - D(0.3)
Decimal('2.775557561565156540423631668E-17')
>>> D('0.1') * D('3') - D('0.3')
Decimal('0.0')
>>> D('2.4').as_integer_ratio()
(12, 5)
>>> 

不可变序列

  • strings(字符串)与bytes(字节):

>>> str1 = 'Hello World'
>>> str2 = "Hello World"
>>> str3 = '''Hello World
... Hello World
... Hello World'''
>>> str4 = """Hello World
... Hello World
... Hello World
... Hello World
... Hello World"""
>>> len(str1)
11
>>> str4
'Hello World\nHello World\nHello World\nHello World\nHello World'
>>> print(str4)
Hello World
Hello World
Hello World
Hello World
Hello World
>>> 
>>> s = "Hello World Long Test Text"
>>> s[0]
'H'
>>> s[6]
'W'
>>> s[:6]
'Hello '
>>> s[6:]
'World Long Test Text'
>>> s[6:26:3]
'WlLge x'
>>> s[:]
'Hello World Long Test Text'
>>> 
  • tuples(元组):

>>> t=()
>>> type(t)
<class 'tuple'>
>>> one_element_tuple=(18,)
>>> three_element_tuple=(18,30,50)
>>> a,b,c=1,2,3
>>> a,b,c
(1, 2, 3)
>>>
>>> a,b=1,2
>>> a,b=b,a
>>> a,b
(2, 1)
>>>

可变序列

  • List:

>>> []
[]
>>> list()
[]
>>> [1,2,3]
[1, 2, 3]
>>> [x + 5 for x in [2,3,4]]
[7, 8, 9]
>>> list((1,3,5,7,9))
[1, 3, 5, 7, 9]
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
>>> 
  • Byte arrays:

>>> bytearray()
bytearray(b'')
>>> bytearray(10)
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> bytearray(range(5))
bytearray(b'\x00\x01\x02\x03\x04')
>>> me = bytearray(b'Paul')
>>> me.endswith(b'l')
True
>>> me.upper()
bytearray(b'PAUL')
>>> me.count(b'l')
1
>>> 

Set类型

  • set 可变
  • frozenset 不可变

>>> s = set()
>>> s.add(2)
>>> s.add(5)
>>> s.add(7)
>>> s
{2, 5, 7}
>>> s.add(1)
>>> s
{1, 2, 5, 7}
>>> s.remove(1)
>>> s
{2, 5, 7}
>>> s.add(5)
>>> s
{2, 5, 7}
>>> s2 = set([5,7,11])
>>> s | s2
{2, 5, 7, 11}
>>> s & s2
{5, 7}
>>> s -  s2
{2}
>>> 
>>> fs = frozenset([2,5,7])
>>> fs.add(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>> fs
frozenset({2, 5, 7})
>>> 

Mapping类型 - dictionaries(字典)

>>> a = dict(A=2, B=3)
>>> b = {'A': 2, 'B': 3}
>>> c = dict(zip(['A', 'B'], [2, 3]))
>>> d = dict([('A',2), ('B',3)])
>>> e = dict({'A': 2, 'B': 3})
>>> a == b == c == d == e
True
>>> 

集合模块

  • namedTuple 工厂方法创建带有名字的tuple
  • deque 列表式容器
  • ChainMap 字典式类 用于创建多个mappings
  • Counter 字典子类 用于计数哈希对象
  • OrderedDict 带顺序的字典子类
  • defaultdict 带默认值的字典子类
  • UserDict 简易的字典对象封装
  • UserList 简易的列表对象封装
  • UserString 简易的字符串对象封装

namedtuple:

>>> from collections import namedtuple
>>> Vision = namedtuple('Vision', ['left', 'right'])
>>> vision = Vision(18,30)
>>> vision.left
18
>>>

枚举类型

>>> from enum import Enum
>>> class TrafficLight(Enum):
...     GREEN=1
...     YELLOW=2
...     RED=3
...
>>> TrafficLight.GREEN
<TrafficLight.GREEN: 1>
>>> TrafficLight.GREEN.name
'GREEN'
>>> TrafficLight.GREEN.value
1
>>>

注意点

  • 很小的值的缓存

>>> a = 1
>>> b = 1
>>> id(a) == id(b)
True
>>> a = 100000
>>> b = 100000
>>> id(a) == id(b)
False
>>>
  • O(n)
  • 索引:

>>> a = list(range(5))
>>> a
[0, 1, 2, 3, 4]
>>> len(a)
5
>>> a[len(a)-1]
4
>>> a[-1]
4
>>> a[-2]
3
>>> a[-5]
0

http://lihuaxi.xjx100.cn/news/362297.html

相关文章

微服务框架 SpringCloud微服务架构 微服务保护 31 限流规则 31.4 流控效果【warm up】

微服务框架 【SpringCloudRabbitMQDockerRedis搜索分布式&#xff0c;系统详解springcloud微服务技术栈课程|黑马程序员Java微服务】 微服务保护 文章目录微服务框架微服务保护31 限流规则31.4 流控效果【warm up】31.4.1 流控效果31.4.2 流控效果 - warm up31.4.3 案例31 限…

笔试强训(四十一)

目录一、选择题二、编程题2.1 Emacs计算器2.1.1 题目2.1.1 题解一、选择题 &#xff08;1&#xff09;某主机的IP地址为180.80.77.55&#xff0c;子网掩码为255.255.252.0.若该主机向其所在子网发送广播分组&#xff0c;则目的地址可以是&#xff08;D&#xff09; A.180.80.7…

如何实现jwt鉴权机制?

一、是什么 JWT&#xff08;JSON Web Token&#xff09;&#xff0c;本质就是一个字符串书写规范&#xff0c;如下图&#xff0c;作用是用来在用户和服务器之间传递安全可靠的信息 在目前前后端分离的开发过程中&#xff0c;使用token鉴权机制用于身份验证是最常见的方案&…

周末福利 | 21天学通Python完整版,豆瓣评分9.6!

前言 又到了周末啦&#xff0c;小编例行给大家发福利&#xff01; 今天福利的内容是21天学通Python完整版&#xff0c;这是一本豆瓣评分9.6的人工智能入门书籍&#xff01;全面、系统、深入地讲解了Python编程基础语法与高级应用。在讲解过程中&#xff0c;通过大量实际操作的…

MySQL 运算符

目录 1. 算术运算符&#xff1a; - * / div % mod 练习&#xff1a; 2. 比较运算符 2.1 <> <> ! < < > > 的使用 <> &#xff1a;安全等于。 记忆技巧&#xff1a;为NULL而生。 #练习&#xff1a;查询表中commission_pct为…

如何搭建SLAM开发环境?

1-1|安装ubuntu和ros 「Ubuntu&ROS」安装Ubuntu系统教程|1-1 「Ubuntu&ROS」Ubuntu系统下搭建深度学习和SLAM开发环境教程|1-2 1-2|g++编译流程 「Ubuntu&ROS」Ubuntu系统下CMake教程|1-5 1-3|CMake编译流程 1-4|Git代码版本控制 「Ubuntu&ROS」U…

crmeb接口未授权,您无法访问,解决方案[400012]Interface is not authorized, you cannot access

crmeb接口未授权,您无法访问,解决方案[400012]Interface is not authorized, you cannot access 报错代码[2021-08-09T10:52:34+08:00][error] [400012]Interface is not authorized, you cannot access[/www/wwwroot/XXXXX.com/app/services/system/admin/SystemRoleService…

产品经理如何有效处理需求变更

在项目立项后,进入需求的沟通,当需求确定后,难免会遇到需求频繁变更的现象,为了避免这样的事情发生,我们应当设立一套规范的需求变更管理。具体怎么做,一起来看看吧。项目立项之后,就进入需求分析阶段,需求变更随之而来。需求的变更是无法避免的,但我们可以通过制定一…