Python 语法糖
-
- 1.两个变量值互换
- 2.连续赋值
- 3.解包
- 4.链式比较
- 5.重复列表
- 6.字典合并
- 7.字符串反转
- 8.列表转字符串
- 9.字典推导式
- 10.拓展列表
- 11.列表负数索引
- 12.列表去重
1.两个变量值互换
a = 1
b = 2
a, b = b, a
>>> a
2
>>> b
1
2.连续赋值
a = b = c = 20
>>> a
20
>>> b
20
>>> c
20
3.解包
a, b, c = [0, 1, 2]
>>> a
0
>>> b
1
>>> c
2
a, *others = [1, 2, 3, 4]
>>> a
1
>>> others
[2, 3, 4]
4.链式比较
a = 15
if (1 < a < 2):
print("true")
5.重复列表
>>> [5, 2] * 3
[5, 2, 5, 2, 5, 2]
6.字典合并
>>> a = {
"a": 1}
>>> b = {
"b": 2}
>>> {
**a, **b}
{
'a': 1, 'b': 2}
7.字符串反转
>>> s = 'hello world'
>>> s[::-1]
'dlrow olleh'
8.列表转字符串
>>> s = ['hello', 'world']
>>> "".join(s)
'helloworld'
9.字典推导式
>>> m = {
X: x**2 for x in range(5)}
>>> m
{
0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
10.拓展列表
>>> i = ['a', 'b', 'c']
>>> i.extend(['e', 'f', 'g'])
>>> i
['a', 'b', 'c', 'e', 'f', 'g']
11.列表负数索引
>>> a = [1, 2, 3]
>>> a[-1]
3
12.列表去重
list0 = [1, 2, 3, 2, 2, 5, 6, 5]
list0 = list(set(list0))
>>> list0
[1, 2, 3, 5, 6]