找回密码
 立即注册
搜索
查看: 255|回复: 0

Python 数据类型与条件运算笔记

[复制链接]

266

主题

0

回帖

1119

积分

管理员

积分
1119
发表于 2024-2-25 10:27:20 | 显示全部楼层 |阅读模式

数据类型

整数、浮点数、字符串(单引号、双引号、三引号、r 标记)、布尔值(True、False)、空值(None)、列表、字典、集合、用户自定义数据类型

字符串

字符串的单引号、双引号基本没有区别。

str 在内存中是用 Unicode 编码的

str 与 bytes 转换

用 ecode() 方法转换为 bytes,用 decode() 方法从 bytes 转换为 str

>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'

注意 b 前缀(表示 bytes)的用法

函数方法

ord():获取字符的整数表示

chr():把编码转换为对应的字符

len():获取字符串长度

>>> len('中文')
2
>>> len(b'\xe4\xb8\xad\xe6\x96\x87')
6
>>> len('中文'.encode('utf-8'))
6

字符串格式化

%d、%f、%s、%x

>>> 'Hi, %s, you have $%d.' % ('Michael', 1000000)
'Hi, Michael, you have $1000000.'
>>> '%2d-%02d' % (3, 1)
' 3-01'
>>> '%.2f' % 3.1415926
'3.14'
>>> 'Age: %s. Gender: %s' % (25, True)
'Age: 25. Gender: True'(注:%s会把任何数据类型转换为字符串)

列表(list)

list 是一种有序的集合,可以随时添加和删除其中的元素。

>>> classmates = ['Michael', 'Bob', 'Tracy']
>>> classmates
['Michael', 'Bob', 'Tracy']

>>> len(classmates)(注:元素个数)
3

>>> classmates[0]
'Michael'
>>> classmates[1]
'Bob'

>>> classmates[-1](注:倒数第一个元素)
'Tracy'
>>> classmates[-2]
'Bob'

>>> classmates.append('Adam') (注:追加元素到末尾)
>>> classmates
['Michael', 'Bob', 'Tracy', 'Adam']

>>> classmates.insert(1, 'Jack')(注:追加元素到某序号之后)
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']

>>> classmates.pop()(注:弹出末尾元素,不要与队列混淆,况且也没有push方法)
'Adam'
>>> classmates
['Michael', 'Jack', 'Bob', 'Tracy']

>>> classmates.pop(1)(注:弹出指定序号元素)
'Jack'
>>> classmates
['Michael', 'Bob', 'Tracy']

>>> classmates[1] = 'Sarah'(注:直接给某元素赋值)
>>> classmates
['Michael', 'Sarah', 'Tracy']

list 里面的元素的数据类型也可以不同

>>> L = ['Apple', 123, True]

list 元素也可以是另一个 list

>>> s = ['python', 'java', ['asp', 'php'], 'scheme']
>>> len(s)
4
>>> s[2][1]
'php'

元组(tuple)

tuple 和 list 非常类似,但是 tuple 一旦初始化就不能修改,所以,自然也没有 append()、insert() 这样的方法。

可以近似地理解为常量数组。

>>> classmates = ('Michael', 'Bob', 'Tracy')
>>> classmates
('Michael', 'Bob', 'Tracy')

只有 1 个元素的 tuple 定义时必须加一个逗号,,来消除歧义:

>>> t = (1)
>>> t(注:此时t的值是整型数值1,而不是一个元组)
1
>>> t = (1,)
>>> t
(1,)

字典(dict)

字典在其他语言中也称为 map,使用键-值(key-value)存储,具有极快的查找速度。

为什么 dict 查找速度这么快?因为 dict 的实现原理和查字典是一样的。假设字典包含了 1 万个汉字,我们要查某一个字,一个办法是把字典从第一页往后翻,直到找到我们想要的字为止,这种方法就是在 list 中查找元素的方法,list 越大,查找越慢。另一种方法是先在字典的索引表里(比如部首表)查这个字对应的页码,然后直接翻到该页,找到这个字。无论找哪个字,这种查找速度都非常快,不会随着字典大小的增加而变慢。

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
>>> d['Michael']
95

>>> d['Adam'] = 67 (注:添加新键值对)
>>> d
{'Adam': 67, 'Tracy': 85, 'Michael': 95, 'Bob': 75}

key 是否存在

>>> 'Thomas' in d
False
>>> d.get('Thomas') (注:返回None)
>>> d.get('Thomas', -1)
-1

弹出一个键值对(删除)

>>> d.pop('Bob')
75
>>> d
{'Adam': 67, 'Tracy': 85, 'Michael': 95}

集合(set)

set 和 dict 类似,也是一组 key 的集合,但不存储 value。由于 key 不能重复,所以,在 set 中,没有重复的 key。这就是数学中集合的概念了。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

重复元素在 set 中自动被过滤:

>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.remove(4) (注:删除一个元素,不能使用pop(4))
>>> s
{1, 2, 3}

两个集合的交集、并集运算

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}

条件运算

if ... elif ... else ...

age = 3
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')

if x: (注:只要x是非零数值、非空字符串、非空list等,就判断为True)
    print('True')

for x in ...

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print(sum)

sum = 0
for x in range(1, 11):
    sum = sum + x
print(sum)

while ...

sum = 0
n = 1
while n <= 10:
    sum = sum + n
    n += 1
print(sum)

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|棱讯科技 ( 粤ICP备2024228160号-2|粤公网安备44030002003510号 )

GMT+8, 2024-7-27 12:39 , Processed in 0.019374 second(s), 4 queries , Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表