·参考

### 循环

ranger(100)表示0到99这一百个数

### 不可变对象

```>>> a = 'abc'
>>> a.replace('a', 'A')
'Abc'
>>> a
'abc'
```

### 列表(list)

```# 向列表追加元素
a = ['hello','h','a','b']
a.append('world')
# 删除列表最后一个元素
a.pop()
```

#### 切片

```# 从a[0]开始到a[2]
a[0:3]
# 或者,省略0
a[:3]
# 省略-1
a[-2:]
# 每两个取一个
a[::2]
```

#### 迭代

```isinstance(x, Iterable)
```

```>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
...
0 A
1 B
2 C
```

#### 列表生成式

```>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 或者
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
# 使用两层循环，生成全排列
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
```

### 元组(tuple)

```# 只有一个元素时
a = ('hello',)
# 而不是
a = ('hello')
```

### 字典(dict)

#### 删除key

```a.pop('hello')
```

#### set

key不会重复

```a = set([1,2,3])
# 添加key到set
# 删除key从set
```

set可以看成数学意义上的无序和无重复元素的集合，因此，两个set可以做数学意义上的交集、并集等操作：

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

#### 迭代key和value

```for k,v in a.items():
print(k,v)
```

### 数据类型转化及内置函数

```# 转换函数
int float str bool
# 数据类型检查
isinstance(x, (int, float))
```

### generator

```>>> g = (x * x for x in range(2))
>>> g
<generator object <genexpr> at 0x1022ef630>
```

#### 输出generator

```>>> next(g)
0
>>> next(g)
1
>>> next(g)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
```

### 函数

#### 可变参数

```def calc(numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
```

```def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
```

```>>> nums = [1, 2, 3]
>>> calc(*nums)
14
```

#### 关键字参数

```def person(name, age, **kw):
print('name:', name, 'age:', age, 'other:', kw)
```

```>>> person('Michael', 30)
name: Michael age: 30 other: {}
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
```

```>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
```

#### 命名关键字参数

```def person(name, age, *, city, job):
print(name, age, city, job)
```