List
列表数据类型有多种方法。 以下是列表对象的所有方法
使用大多数列表方法的示例:
>>> fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
>>> fruits.count('apple')
2
>>> fruits.count('tangerine')
0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting a position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'
Using Lists as Stacks
list方法可以很容易地将列表用作堆栈,其中添加的最后一个元素是检索到的第一个元素(“last-in,first-out”)。
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
Using Lists as Queues
也可以使用列表作为队列,其中添加的第一个元素是检索的第一个元素(“先进先出”); 要实现队列,请使用collections.deque,它的设计具有快速追加和两端弹出特性。 例如:
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
The del statement
这是一种从给定索引而不是其值的列表中删除项目的方法:del语句。 这与返回值的pop()方法不同。
>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0]
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4]
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]
Sets
Python还包括集合的数据类型。 集合是无序集合,没有重复元素。 基本用途包括成员资格检测和消除重复条目。
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket) # show that duplicates have been removed
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
>>> # Demonstrate set operations on unique letters from two words
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Dictionaries
Python内置的另一个有用的数据类型是字典(请参阅映射类型 - 字典)。 词典有时在其他语言中被称为“关联记忆”或“关联阵列”。 与通过一系列数字索引的序列不同,字典由键索引,键可以是任何不可变类型;
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'jack': 4098, 'sape': 4139, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'guido': 4127, 'irv': 4127}
>>> list(tel)
['jack', 'guido', 'irv']
>>> sorted(tel)
['guido', 'irv', 'jack']
>>> 'guido' in tel
True
>>> 'jack' not in tel
False
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
...
gallahad the pure
robin the brave
Module
如果退出Python解释器并再次输入,则所做的定义(函数和变量)将丢失。 因此,如果要编写更长的程序,最好使用文本编辑器为解释器准备输入,并将该文件作为输入运行。 这称为创建脚本。
为了支持这一点,Python有一种方法可以将定义放在一个文件中,并在脚本或解释器的交互式实例中使用它们。 这样的文件称为模块; 模块中的定义可以导入到其他模块或主模块中
模块是包含Python定义和语句的文件。 文件名是附加后缀.py的模块名称。 在模块中,模块的名称(作为字符串)可用作全局变量__name__的值。 例如,使用您喜欢的文本编辑器在当前目录中创建一个名为fibo.py的文件,其中包含以下内容:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
>>> import fibo
>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'
>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
模块可以包含可执行语句以及函数定义。 这些语句用于初始化模块。 它们仅在第一次在import语句中遇到模块名时执行。 [1](如果文件作为脚本执行,它们也会运行。)
每个模块都有自己的私有变量表,该表用作模块中定义的所有函数的全局变量表。 因此,模块的作者可以在模块中使用全局变量,而不必担心与用户的全局变量的意外冲突。
当你运行Python模块时
python fibo.py <arguments>
The Module Search Path
导入名为spam的模块时,解释器首先搜索具有该名称的内置模块。 如果未找到,则会在变量sys.path给出的目录列表中搜索名为spam.py的文件。 sys.path从这些位置初始化:
包含输入脚本的目录(或未指定文件时的当前目录)。
PYTHONPATH(目录名列表,语法与shell变量PATH相同)。
依赖于安装的默认值。
“Compiled” Python files
为了加速加载模块,Python将每个模块的编译版本缓存在名为module.version.pyc的pycache目录中,其中版本对编译文件的格式进行编码; 它通常包含Python版本号。 例如,在CPython版本3.3中,spam.py的编译版本将缓存为pycache / spam.cpython-33.pyc。 此命名约定允许来自不同版本和不同版本的Python的已编译模块共存。
The dir() Function
内置函数dir()用于找出模块定义的名称。 它返回一个排序的字符串列表:
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__loader__', '__name__',
'__package__', '__stderr__', '__stdin__', '__stdout__',
'_clear_type_cache', '_current_frames', '_debugmallocstats', '_getframe',
'_home', '_mercurial', '_xoptions', 'abiflags', 'api_version', 'argv',
'base_exec_prefix', 'base_prefix', 'builtin_module_names', 'byteorder',
'call_tracing', 'callstats', 'copyright', 'displayhook',
'dont_write_bytecode', 'exc_info', 'excepthook', 'exec_prefix',
'executable', 'exit', 'flags', 'float_info', 'float_repr_style',
'getcheckinterval', 'getdefaultencoding', 'getdlopenflags',
'getfilesystemencoding', 'getobjects', 'getprofile', 'getrecursionlimit',
'getrefcount', 'getsizeof', 'getswitchinterval', 'gettotalrefcount',
'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
'intern', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path',
'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1',
'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit',
'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
'thread_info', 'version', 'version_info', 'warnoptions']
Packages
包是一种使用“点模块名称”构造Python模块命名空间的方法。 例如,模块名称AB在名为A的包中指定名为B的子模块。就像使用模块保存不同模块的作者不必担心彼此的全局变量名一样,使用点模块名称可以保存作者 NumPy或Pillow等多模块软件包不必担心彼此的模块名称。