暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python内置(5)容器、字节、类型转换、format

一只大鸽子 2022-10-08
445

list, tuple, dict, set and frozenset: The containers

Python中的“容器”是指可以在其中保存任意数量项的数据结构。

Python 有 5 种基本容器类型: list
:有序、有索引的容器。每个元素都存在于特定的索引处。列表是可变的,即可以随时添加或删除项目。 tuple
:有序、有索引,就像列表一样,但有一个关键区别:tuple
是不可变的,这意味着一旦创建元组,就无法添加或删除项目。 dict
: 无序键值对。键用于访问对应的值。键-值是一一对应的。 set
:无序、不重复的数据集合。集合中的项目仅表示它们的存在或不存在。例如,您可以使用集合来查找森林中的树木种类。他们的顺序并不重要,重要的是他们是否存在。 frozenset
,类似set
,但不可变。

bytearray and memoryview: 更好的byte接口

bytearray
bytes
对象的可变等效物,就像列表是可变元组。 bytearray
很有用,因为:

  • • 许多低级交互都与字节和位操作有关,就像str.upper
    ,所以有一个字节数组,你可以改变单个字节,这将更加高效。

  • • bytes具有固定大小(即...1 字节)。另一方面,由于 unicode 编码标准“utf-8”,字符串字符可以具有各种大小:

>>> x = 'I♥🐍'
>>> len(x)
3
>>> x.encode()
b'I\xe2\x99\xa5\xf0\x9f\x90\x8d'
>>> len(x.encode())
8
>>> x[2]
'🐍'
>>> x[2].encode()
b'\xf0\x9f\x90\x8d'
>>> len(x[2].encode())
4

三个字符长的字符串“I♥🐍”实际上是八个字节,蛇表情符号的长度为4个字节。但是,在它的编码版本中,我们可以访问每个单独的字节。因为它是一个字节,它的“值”将始终介于 0 和 255 之间:

>>> x[2]
'🐍'
>>> b = x[2].encode()
>>> b
b'\xf0\x9f\x90\x8d'  # 4 bytes
>>> b[:1]
b'\xf0'
>>> b[1:2]
b'\x9f'
>>> b[2:3]
b'\x90'
>>> b[3:4]
b'\x8d'
>>> b[0]  # indexing a bytes object gives an integer
240
>>> b[3]
141

同时,memoryview
将这个想法更进一步:它几乎就像一个bytearray,但它可以通过引用来引用对象或切片,而不是为自己创建新的副本。它允许您将引用传递给内存中的字节部分,并对其进行就地编辑:

>>> array = bytearray(range(256))
>>> array
bytearray(b'\x00\x01\x02\x03\x04\x05\x06\x07\x08...
>>> len(array)
256
>>> array_slice = array[65:91]  # Bytes 65 to 90 are uppercase english characters
>>> array_slice
bytearray(b'
ABCDEFGHIJKLMNOPQRSTUVWXYZ')
>>> view = memoryview(array)[65:91]  # Does the same thing,
>>> view
<memory at 0x7f438cefe040>  # but doesn'
t generate a new new bytearray by default
>>> bytearray(view)
bytearray(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')  # It can still be converted, though.
>>> view[0]  # 'A'
65
>>> view[0] += 32  # Turns it lowercase
>>> bytearray(view)
bytearray(b'aBCDEFGHIJKLMNOPQRSTUVWXYZ')  # 'A' is now lowercase.
>>> bytearray(view[10:15])
bytearray(b'KLMNO')
>>> view[10:15] = bytearray(view[10:15]).lower()
>>> bytearray(view)
bytearray(b'aBCDEFGHIJklmnoPQRSTUVWXYZ')  # Modified 'KLMNO' in-place.

bin, hex, oct, ord, chr and ascii: 基本转换

bin
,hex
,oct
分别是2进制、16进制、8进制,可用于整数的进制转换。

>>> bin(42)
'0b101010'
>>> hex(42)
'0x2a'
>>> oct(42)
'0o52'
>>> 0b101010
42
>>> 0x2a
42
>>> 0o52
42

ord
chr
用于转换 ascii 以及 unicode 字符及其字符代码:

>>> ord('x')
120
>>> chr(120)
'x'
>>> ord('🐍')
128013
>>> hex(ord('🐍'))
'0x1f40d'
>>> chr(0x1f40d)
'🐍'
>>> '\U0001f40d'  # The same value, as a unicode escape inside a string
'🐍'

format: Easy text transforms

format(string, spec)
 等同于 string.format(spec)
。简单的字符串格式化。


文章转载自一只大鸽子,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论