第1章、基础

1、几个小知识点

  • 多用 help() 帮助文档
  • 除法运算
/  除法运算,得到结果为浮点数;
// 整除运算,得到整数值(向下取整);
% 取余操作 (结果符号与除数符号相同),本质上: x % y = x - (x // y) * y >>> 10 % 3
1
>>> -10 % 3
2
>>> 10 % -3
-2
>>> -10 % -3
-1
>>> 3 % 10
3
>>> -3 % 10
7
>>> 3 % -10
-7
>>> -3 % -10
-3
  • 进制
十六进制  0x开头
八进制 0开头
二进制 0b开头 >>> 0xAF
175
>>> 010
8
>>> 0b1011010010
722
  • 变量

Python变量没有默认值;

表达式是一些东西,而语句做一些事情

  • 获取键盘输入
input()函数,返回字符串

>>> x = input("x: ")
x: 34
>>> y = input("y: ")
y: 42
>>> print(int(x) * int(y))
1428
  • 内置函数和模块
>>> 2 ** 3
8
>>> pow(2,3)
8 >>> abs(-10)
10 >>> 2 // 3
0
>>> round(2/3)
1
>>> round(1.4)
1
>>> round(1.5) # 偶数
2
>>> round(1.6)
2
>>> round(2.5) # 偶数
2
>>> round(2.55, 1)
2.5 >>> int(30.4)
30
>>> import math # 导入模块
>>> math.floor(30.4)
30
>>> math.ceil(30.4)
31 >>> from math import sqrt # 从模块中导入函数
>>> sqrt(9)
3.0 >>> sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error # 复数模块
>>> import cmath
>>> cmath.sqrt(-1)
1j >>> cmath.sqrt(-8j)
(2-2j)

2、字符串

  • 单引号、双引号、三引号、反斜杠
  • 字符串拼接 +
  • str 与 repr
>>> print(repr("Hello,\nworld!"))  # 面向程序表达式
'Hello,\nworld!'
>>> print(str("Hello,\nworld!")) # 面向用户
Hello,
world!
  • 原始字符串:原始含反斜杠的字符串,如:路径。
"""
加反斜杠转义;
字符串前加r,作为原始字符串不被转义
""" >>> print("C:\now")
C:
ow >>> print("C:\\now")
C:\now >>> print(r"C:\now")
C:\now #注意:反斜杠结尾的字符串
>>> print(r"C:\now\day\")
File "<stdin>", line 1
print(r"C:\now\day\")
^
SyntaxError: EOL while scanning string literal >>> print(r"C:\now\day" + "\\")
C:\now\day\
  • Unicode:码点和名称 (简单了解)

    • 使用16或32位的十六进制字面量(分别加上前缀\u或\U)

    • 使用字符的Unicode名称(\N{name})

  • 字节类型:不可变的bytes 和 可变的bytearray。 'b'开头

    • Python bytes字面量只支持ASCII标准中的128个字符,而余下的128个值必须用转义序列表示
    • 进行单字节编码时,依然使用ASCII编码,以便与较旧的系统兼容;但对于不在这个范围内的字符,使用多个字节(最多为6个)进行编码
    >>> b'Hello, world!'
    b'Hello, world!' >>> "Hello, world!".encode("ASCII")
    b'Hello, world!'
    >>> "Hello, world!".encode("UTF-8")
    b'Hello, world!'
    >>> "Hello, world!".encode("UTF-32")
    b'\xff\xfe\x00\x00H\x00\x00\x00e\x00\x00\x00l\x00\x00\x00l\x00\x00\x00o\x00\x00\x00,\x00\x00\x00\x00\x00\x00w\x00\x00\x00o\x00\x00\x00r\x00\x00\x00l\x00\x00\x00d\x00\x00\x00!\x00\x00\x00' >>> len("How long is this?".encode("UTF-8"))
    17
    >>> len("How long is this?".encode("UTF-32"))
    72 >>> bytes("Hællå, wørld!", encoding="utf-8")
    b'H\xc3\xa6ll\xc3\xa5, w\xc3\xb8rld!'
    >>> str(b'H\xc3\xa6ll\xc3\xa5, w\xc3\xb8rld!', encoding="utf-8")
    'Hællå, wørld!'
    >>> x = bytearray(b"Hello!")
    >>> x[1] = ord(b"u")
    >>> x
    bytearray(b'Hullo!') >>> chr(65)
    'A'
    >>> ord("A")
    65

第2章 列表与元组

1、序列

  • 列表是可以修改的,而元组不可以

  • 索引、切片、相加、相乘和成员资格检查

  • 确定序列的长度以及找出序列中最大和最小的元素

  • 迭代

>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6] # 初始化10个元素的列表
>>> sequence = [None] * 10
>>> sequence
[None, None, None, None, None, None, None, None, None, None] in
not in >>> "yt" in "Python"
True
>>> "x" in "Python"
False >>> "a" in ["a", "b", 0]
True
>>> "0" in ["a", "b", 0]
False len(list)、max(list)、min(list)

2、列表

# 字符串 转 列表
>>> list('Hello')
['H', 'e', 'l', 'l', 'o'] >>> "H-e-l-l-o".split("-")
['H', 'e', 'l', 'l', 'o'] # 列表 转 字符串
>>> "".join(['H', 'e', 'l', 'l', 'o'])
'Hello'
>>> "-".join(['H', 'e', 'l', 'l', 'o'])
'H-e-l-l-o' # 修改列表:给元素赋值
>>> x = [1, 1, 1]
>>> x[1] = 2
>>> x
[1, 2, 1] # 删除元素
>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
>>> del names[2]
>>> names
['Alice', 'Beth', 'Dee-Dee', 'Earl'] # 给切片赋值
>>> name = list('Perl')
>>> name
['P', 'e', 'r', 'l']
>>> name[2:] = list('ar')
>>> name
['P', 'e', 'a', 'r'] >>> name = list('Perl')
>>> name[1:] = list('ython')
>>> name
['P', 'y', 't', 'h', 'o', 'n'] >>> numbers
[1, 2, 3, 4, 5]
>>> numbers[1:4] = []
>>> numbers
[1, 5] # append 就地添加
>>> lst = [1, 2, 3]
>>> lst.append(4)
>>> lst
[1, 2, 3, 4] # clear 就地清空
>>> lst = [1, 2, 3]
>>> lst.clear()
>>> lst
[] # copy 复制成副本 等价于 a[:]或list(a)
>>> a = [1, 2, 3]
>>> b = a
>>> b[1] = 4
>>> a
[1, 4, 3] >>> a = [1, 2, 3]
>>> b = a.copy()
>>> b[1] = 4
>>> a
[1, 2, 3] # count计数指定元素出现次数
>>> ['to', 'be', 'or', 'not', 'to', 'be'].count('to')
2
>>> x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>> x.count(1)
2
>>> x.count([1, 2])
1 # index在列表中查找指定值第一次出现的索引。
>>> knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>> knights.index('who')
4
>>> knights.index('herring')
Traceback (innermost last):
File "<pyshell>", line 1, in ?
knights.index('herring')
ValueError: list.index(x): x not in list # extend 就地拼接,效率高
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a.extend(b)
>>> a
[1, 2, 3, 4, 5, 6] >>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a + b
[1, 2, 3, 4, 5, 6]
>>> a
[1, 2, 3] # insert >>> numbers = [1, 2, 3, 5, 6, 7]
>>> numbers.insert(3, 'four')
>>> numbers
[1, 2, 3, 'four', 5, 6, 7] # pop从列表中删除一个元素(末尾为最后一个元素),并返回这一元素。
>>> x = [1, 2, 3]
>>> x.pop()
3
>>> x
[1, 2]
>>> x.pop(0)
1
>>> x
[2] # remove用于删除第一个为指定值的元素,就地删除,不返回值
>>> x = ['to', 'be', 'or', 'not', 'to', 'be']
>>> x.remove('be')
>>> x
['to', 'or', 'not', 'to', 'be']
>>> x.remove('bee')
Traceback (innermost last):
File "<pyshell>", line 1, in ?
x.remove('bee')
ValueError: list.remove(x): x not in list # reverse按相反的顺序排列列表中的元素,就地修改
>>> x = [1, 2, 3]
>>> x.reverse()
>>> x
[3, 2, 1] >>> x = [1, 2, 3]
>>> list(reversed(x))
[3, 2, 1] # sort用于对列表就地排序,返回None
>>> x = [4, 6, 2, 1, 7, 9]
>>> x.sort()
>>> x
[1, 2, 4, 6, 7, 9] >>> x = [4, 6, 2, 1, 7, 9]
>>> y = sorted(x)
>>> x
[4, 6, 2, 1, 7, 9]
>>> y
[1, 2, 4, 6, 7, 9] >>> sorted('Python')
['P', 'h', 'n', 'o', 't', 'y'] list.sort(cmp=None, key=None, reverse=False)
sorted(iterable, cmp=None, key=None, reverse=False)
  • 可以用append和pop实现 栈结构

3、元组

>>> 42
42
>>> 42,
(42,) >>> 3 * (40 + 2)
126
>>> 3 * (40 + 2,)
(42, 42, 42)

第3章 字符串

  • 索引、切片、乘法、成员资格检查、长度、最小值和最大值

1、格式化

# 1、%
>>> "Hello, %s. %s enough for ya?" % ('world', 'Hot')
'Hello, world. Hot enough for ya?' # 2、Template $
>>> from string import Template
>>> Template("Hello, $who! $what enough for ya?").substitute(who="Mars", what="Dusty")
'Hello, Mars! Dusty enough for ya?' # format 推荐
## 位置
>>> "{}, {} and {}".format("first", "second", "third")
'first, second and third'
>>> "{0}, {1} and {2}".format("first", "second", "third")
'first, second and third' ## 索引可乱序
>>> "{3} {0} {2} {1} {3} {0}".format("be", "not", "or", "to")
'to be or not to be' ## 关键字参数:变量名
>>> from math import pi
>>> "{name} is approximately {value:.2f}.".format(value=pi, name="π")
'π is approximately 3.14.' ## f字符串
>>> from math import e
>>> f"Euler's constant is roughly {e}."
"Euler's constant is roughly 2.718281828459045."
# format 每个值都被插入字符串中,以替换用花括号括起的替换字段
"""
字段名:索引或标识符,指出要设置哪个值的格式并使用结果来替换该字段。除指定值外,还可指定值的特定部分,如列表的元素。
"""
>>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3)
'3 1 4 2' >>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3)
'3 2 4 1' >>> "Mr {name[1]}".format(name=["Alfred", "Smoketoomuch"])
'Mr Smoketoomuch' >>> import math
>>> "The {mod.__name__} module defines the value {mod.pi} for π".format(mod=math)
'The math module defines the value 3.141592653589793 for π' """
转换标志:跟在叹号后面的单个字符。当前支持的字符包括r(表示repr)、s(表示str)和a(表示ascii)。如果你指定了转换标志,将不使用对象本身的格式设置机制,而是使用指定的函数将对象转换为字符串,再做进一步的格式设置。
"""
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π"))
π 'π' '\u03c0' >>> "The number is {num}, {num:f}, {num:b}".format(num=42)
'The number is 42, 42.000000, 101010' ## 宽度
>>> "{num:10}".format(num=3)
' 3'
>>> "{name:10}".format(name="Bob")
'Bob ' ## 精度
>>> "Pi day is {pi:.2f}".format(pi=pi)
'Pi day is 3.14' >>> "{pi:10.2f}".format(pi=pi)
' 3.14' >>> "{:.5}".format("Guido van Rossum")
'Guido' ## 千位分隔符
>>> 'One googol is {:,}'.format(10**100)
'One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000' """
格式说明符:跟在冒号后面的表达式(这种表达式是使用微型格式指定语言表示的)。格式说明符让我们能够详细地指定最终的格式,包括格式类型(如字符串、浮点数或十六进制数),字段宽度和数的精度,如何显示符号和千位分隔符,以及各种对齐和填充方式。
"""
>>> '{:010.2f}'.format(pi)
'0000003.14' ## 左对齐、右对齐和居中
>>> print('{0:<10.2f}\n{0:^10.2f}\n{0:>10.2f}'.format(pi))
3.14
3.14
3.14 >>> "{:$^15}".format(" WIN BIG ")
'$$$ WIN BIG $$$' >>> print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
3.14
-3.14
>>> print('{0:10.2f}\n{1:10.2f}'.format(pi, -pi))
3.14
-3.14 >>> print('{0:10.2f}\n{1:=10.2f}'.format(pi, -pi))
3.14
- 3.14 >>> print('{0:-.2}\n{1:-.2}'.format(pi, -pi)) #默认设置
3.1
-3.1
>>> print('{0:+.2}\n{1:+.2}'.format(pi, -pi))
+3.1
-3.1
>>> print('{0: .2}\n{1: .2}'.format(pi, -pi))
3.1
-3.1 >>> "{:b}".format(42)
'101010'
>>> "{:#b}".format(42)
'0b101010' >>> "{:g}".format(42)
'42'
>>> "{:#g}".format(42)
'42.0000'

2、字符串方法

# center通过在两边添加填充字符(默认为空格)让字符串居中。  ljust、rjust和zfill
>>> "The Middle by Jimmy Eat World".center(39)
' The Middle by Jimmy Eat World '
>>> "The Middle by Jimmy Eat World".center(39, "*")
'*****The Middle by Jimmy Eat World*****' # find 在字符串中查找子串。如果找到,就返回子串的第一个字符的索引,否则返回-1。 rfind、index、rindex、count、startswith、endswith
>>> 'With a moo-moo here, and a moo-moo there'.find('moo')
7
>>> title = "Monty Python's Flying Circus"
>>> title.find('Python')
6
>>> title.find('Zirquss')
-1 >>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$', 1) # 只指定了起点
20
>>> subject.find('!!!')
16
>>> subject.find('!!!', 0, 16) # 同时指定了起点和终点
-1 # join 合并序列的元素 >>> seq = [1, 2, 3, 4, 5]
>>> sep = '+'
>>> sep.join(seq) # 尝试合并一个数字列表
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: sequence item 0: expected string, int found
>>> seq = ['1', '2', '3', '4', '5']
>>> sep.join(seq) # 合并一个字符串列表
'1+2+3+4+5'
>>> print('C:' + '\\'.join(dirs))
C:\usr\bin\env # lower、capitalize、casefold、swapcase、title、upper # replace 指定子串都替换为另一个字符串,并返回替换后的结果
>>> 'This is a test'.replace('is', 'eez')
'Theez eez a test' # split 用于将字符串拆分为序列
>>> '1+2+3+4+5'.split('+')
['1', '2', '3', '4', '5']
>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 'Using the default'.split()
['Using', 'the', 'default'] # strip 将字符串开头和末尾的空白(但不包括中间的空白)删除,并返回删除后的结果; lstrip、rstrip
>>> ' internal whitespace is kept '.strip()
'internal whitespace is kept' >>> names = ['gumby', 'smith', 'jones']
>>> name = 'gumby '
>>> if name in names: print('Found it!')
...
>>> if name.strip() in names: print('Found it!')
...
Found it! >>> '*** SPAM * for * everyone!!! ***'.strip(' *!')
'SPAM * for * everyone' # translate 进行单字符替换;同时替换多个字符
>>> table = str.maketrans('cs', 'kz')
>>> table
{115: 122, 99: 107}
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt' >>> table = str.maketrans('cs', 'kz', ' ')
>>> 'this is an incredible test'.translate(table)
'thizizaninkredibletezt' # 判断字符串是否满足特定的条件
"""
isalnum、isalpha、isdecimal、isdigit、isidentifier、islower、isnumeric、
isprintable、isspace、istitle、isupper
"""

第4章 字典

  • 字典由键及其相应的值组成,这种键-值对称为项(item)
## 字典
>>> items = [('name', 'Gumby'), ('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'} >>> d = dict(name='Gumby', age=42)
>>> d
{'age': 42, 'name': 'Gumby'} """
len(d) 返回字典d包含的项(键-值对)数。
d[k] 返回与键k相关联的值。
d[k] = v 将值v关联到键k。
del d[k] 删除键为k的项。
k in d 检查字典d是否包含键为k的项。
""" """
键的类型:字典中的键可以是任何不可变的类型,如整数、浮点数(实数)、字符串或元组。 自动添加:即便是字典中原本没有的键,也可以给它赋值,这将在字典中创建一个新项。 成员资格:表达式k in d(其中d是一个字典)查找的是键而不是值。
""" # 通过字典 格式化字符串
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
>>> "Cecil's phone number is {Cecil}.".format_map(phonebook)
"Cecil's phone number is 3258." # clear删除所有的字典项,就地执行,返回None。
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x = {}
>>> y
{'key': 'value'}
下面是第二个场景:
>>> x = {}
>>> y = x
>>> x['key'] = 'value'
>>> y
{'key': 'value'}
>>> x.clear()
>>> y
{} ## copy返回一个新字典,其包含的键值对与原来的字典相同,浅复制
>>> x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
>>> y = x.copy()
>>> y['username'] = 'mlh'
>>> y['machines'].remove('bar')
>>> y
{'username': 'mlh', 'machines': ['foo', 'baz']}
>>> x
{'username': 'admin', 'machines': ['foo', 'baz']} ## deepcopy 深复制
>>> from copy import deepcopy
>>> d = {}
>>> d['names'] = ['Alfred', 'Bertrand']
>>> c = d.copy()
>>> dc = deepcopy(d)
>>> d['names'].append('Clive')
>>> c
{'names': ['Alfred', 'Bertrand', 'Clive']}
>>> dc
{'names': ['Alfred', 'Bertrand']} # fromkeys创建一个新字典,其中包含指定的键,且每个键对应的值都是None
>>> {}.fromkeys(['name', 'age'])
{'age': None, 'name': None} >>> dict.fromkeys(['name', 'age'])
{'age': None, 'name': None} >>> dict.fromkeys(['name', 'age'], '(unknown)')
{'age': '(unknown)', 'name': '(unknown)'} ## get
>>> d = {}
>>> print(d['name'])
Traceback (most recent call last):
File "<stdin>", line 1, in ?
KeyError: 'name' >>> print(d.get('name'))
None >>> d.get('name', 'N/A')
'N/A' ## items返回一个包含所有字典项的列表,其中每个元素都为(key, value)的形式(字典视图)。字典项在列表中的排列顺序不确定。
>>> d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0}
>>> d.items()
dict_items([('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')])
# 字典视图不复制,它们始终是底层字典的反映
>>> it = d.items()
>>> len(it)
3
>>> ('spam', 0) in it
True
>>> d['spam'] = 1
>>> ('spam', 0) in it
False
>>> d['spam'] = 0
>>> ('spam', 0) in it
True ## keys返回一个字典视图,其中包含指定字典中的 ## pop可用于获取与指定键相关联的值,并将该键值对从字典中删除。
>>> d = {'x': 1, 'y': 2}
>>> d.pop('x')
1
>>> d
{'y': 2} ## popitem 随机地弹出一个字典项
>>> d = {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
>>> d.popitem()
('url', 'http://www.python.org')
>>> d
{'spam': 0, 'title': 'Python Web Site'} ## setdefault 获取与指定键相关联的值
>>> d = {}
>>> d.setdefault('name', 'N/A')
'N/A'
>>> d
{'name': 'N/A'}
>>> d['name'] = 'Gumby'
>>> d.setdefault('name', 'N/A')
'Gumby'
>>> d
{'name': 'Gumby'} ## update使用一个字典中的项来更新另一个字典。(字典拼接) ## values返回一个由字典中的值组成的字典视图,可以重复
>>> d = {}
>>> d[1] = 1
>>> d[2] = 2
>>> d[3] = 3
>>> d[4] = 1
>>> d.values()
dict_values([1, 2, 3, 1])

第5章 print和import

1、print

print(*objects, sep=' ', end='\n', file=sys.stdout)

2、import

import somemodule
from somemodule import somefunction
from somemodule import somefunction, anotherfunction, yetanotherfunction
from somemodule import *
froom module1.module2 import somefunction
import somemodule as othername

3、序列解包

# 可同时(并行)给多个变量赋值
>>> x, y, z = 1, 2, 3
>>> print(x, y, z)
1 2 3 # 交换变量值
>>> x, y = y, x
>>> print(x, y, z)
2 1 3 # 解包
>>> values = 1, 2, 3
>>> values
(1, 2, 3)
>>> x, y, z = values
>>> x
1 # 字典解包
>>> scoundrel = {'name': 'Robin', 'girlfriend': 'Marion'}
>>> key, value = scoundrel.popitem()
>>> key
'girlfriend'
>>> value
'Marion' # 序列包含的元素个数必须与你在等号左边列出的目标个数相同 >>> a, b, *rest = [1, 2, 3, 4]
>>> rest
[3, 4] >>> name = "Albus Percival Wulfric Brian Dumbledore"
>>> first, *middle, last = name.split()
>>> middle
['Percival', 'Wulfric', 'Brian'] >>> a, *b, c = "abc"
>>> a, b, c
('a', ['b'], 'c') # 链式赋值
x = y = somefunction() 等价于
y = somefunction()
x = y # 增强赋值
x += 1

4、缩进

5、条件

False None 0 "" () [] {}

bool([]) == bool("") == False

# 链式比较
0 < age < 100 # is is not in not in
# is:相同运算符
# ==用来检查两个对象是否相等,而is用来检查两个对象是否相同(是同一个对象)。
>>> x = y = [1, 2, 3]
>>> z = [1, 2, 3]
>>> x == y
True
>>> x == z
True
>>> x is y
True
>>> x is z
False # in:成员资格运算符 # 字符串和序列的比较
# 字母排列顺序,但字母都是Unicode字符,它们是按码点排列的
>>> "alpha" < "beta"
True >>> "a" < "B"
False >>> [1, 2] < [2, 1]
True >>> [2, [1, 4]] < [2, [1, 5]]
True # 短路逻辑 and or not

6、断言

# assert 检查点
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError # 加断言检查异常说明
>>> age = -1
>>> assert 0 < age < 100, 'The age must be realistic'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: The age must be realistic

6、循环

"""
while、for """ for number in range(1,101):
print(number) # 无序
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key]) for key, value in d.items():
print(key, 'corresponds to', value)

7、迭代工具

names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
# 并行迭代
>>> list(zip(names, ages))
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)] for name, age in zip(names, ages):
print(name, 'is', age, 'years old') # 当序列的长度不同时,函数zip将
# 在最短的序列用完后停止“缝合”。
>>> list(zip(range(5), range(100000000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] # 迭代时取索引
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
# 反向迭代和排序后再迭代
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'

8、跳出循环

break
continue
while True/break

Python基础教程(第3版)学习笔记的更多相关文章

  1. HTML5与CSS3基础教程第八版学习笔记11~15章

    第十一章,用CSS进行布局 开始布局注意事项 1.内容与显示分离 2.布局方法:固定宽度和响应式布局 固定宽度,整个页面和每一栏都有基于像素的宽度 响应式布局也称为流式页面,使用百分数定义宽度 3.浏 ...

  2. HTML5与CSS3基础教程第八版学习笔记16-21章

    第十六章,表单 HTML5引入了新的表单元素.输入类型和属性,以及内置的对必填字段.电子邮件地址.URL以及定制模式验证. 元素: <input type="email"&g ...

  3. HTML5与CSS3基础教程第八版学习笔记7~10章

    第七章,CSS构造块 CSS里有控制基本格式的属性(font-size,color),有控制布局的属性(position,float),还有决定访问者打印时在哪里换页的打印控制元素.CSS还有很多控制 ...

  4. HTML5与CSS3基础教程第八版学习笔记1~6章

    第一章,网页的构造块 网页主要包括三个部分: 1.文本内容(纯文字) 2.对其他文件的引用:图像,音频,视频,样式表文件,js文件 3.标记:对文本内容进行描述并确保引用正确地工作 注:所有这些成分都 ...

  5. Python 基础教程(第二版)笔记 (2) 字典

    P59 字典方法 1. clear 2. copy, deepcopy 3. fromkeys 4. get 比下标安全 5. has_key 6. items, iteritems 7. keys, ...

  6. Python 基础教程(第二版)笔记 (1)

    P22 除非对 input 有特别的需要,否则应该尽可能使用 raw_input 函数. 长字符串,跨多行,用三个引号代替普通引号.并且不需要使用反斜线进行转义. P23 原始字符串 print r' ...

  7. 《python基础教程(第二版)》学习笔记 文件和素材(第11章)

    <python基础教程(第二版)>学习笔记 文件和素材(第11章) 打开文件:open(filename[,mode[,buffering]]) mode是读写文件的模式f=open(r' ...

  8. 《python基础教程(第二版)》学习笔记 类和对象(第7章)

    <python基础教程(第二版)>学习笔记 类和对象(第7章) 定义类class Person:    def setName(self,name):        self.name=n ...

  9. 《python基础教程(第二版)》学习笔记 函数(第6章)

    <python基础教程(第二版)>学习笔记 函数(第6章) 创建函数:def function_name(params):  block  return values 记录函数:def f ...

  10. 《python基础教程(第二版)》学习笔记 语句/循环/条件(第5章)

    <python基础教程(第二版)>学习笔记 语句/循环/条件(第5章) print 'AB', 123 ==> AB 123 # 插入了一个空格print 'AB', 'CD' == ...

随机推荐

  1. HDU 6112 今夕何夕 (预处理 枚举)

    中文题意都看的懂啦~ 思路很简单,就是通过前一天推出当天是星期几,直接枚举所有2017-9999年的每一天就好了.ㄟ( ▔, ▔ )ㄏ 代码: #include <cstdio> #def ...

  2. 第三方软件 G6ftp提权

    步骤 1.下载配置文件 将administrator 2.利用lcx 端口转发 默认只允许本机连接 3.lcx.exe -tran 8027 127.0.0.1 8021 4.使用客户端以管理员用户登 ...

  3. 01jmeter-beanshell常用代码段

    1.获取时间 import java.util.*; import java.text.SimpleDateFormat; String str1 = (new SimpleDateFormat(&q ...

  4. 1.在ubuntu中软件安装在哪里?

    ubuntu下安装软件有四种方式: 1.通过deb格式的离线软件包安装 sudo dpkg -i xxx.deb # 安装包,安装程序   -i: install sudo dpkg -r packa ...

  5. HDFS概述(一)

    HDFS概述(一) 1. HDFS产出的背景及定义 1.1 HDFS产生的背景 随着数据量越来越大,在一个操作系统存不下所有的数据,那么就分配到更多的操作系统管理的磁盘中,但是不方便管理和维护,迫切需 ...

  6. (三)django--带Template的网站

    我们接着(二),在new下新建一个templates(注意必须是这个名字,不然要进行配置),然后在该目录下新建一个test.html 2.我们在pycharm中新建的html文件里面不会有内容,我们输 ...

  7. class样式的添加和设置.html

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  8. accesskey附上一些实例

    HTML accesskey属性与web自定义键盘快捷访问 本文地址:http://www.zhangxinxu.com/wordpress/?p=6142 可能很多小伙伴都不知道,我们只要在HTML ...

  9. 基于AOP和Redis实现对接口调用情况的监控及IP限流

    目录 需求描述 概要设计 代码实现 参考资料 需求描述 项目中有许多接口,现在我们需要实现一个功能对接口调用情况进行统计,主要功能如下: 需求一:实现对每个接口,每天的调用次数做记录: 需求二:如果某 ...

  10. python:__name__的使用

    1.python中__name__是什么意思? 很多python的初学者可能都会遇到一个问题:__name__是什么意思? 在刚开始学习python的时候,我们总会看到这样一句代码: if __nam ...