1. 变量交换
a
= 1
b
= 2
a
, b
= b
, a
a
, b
(2, 1)
2. 字符串格式化
name
= 'Jack'
country
= 'China'
age
= 18
print("Hi, I'm " + name
+ ". I'm from " + country
+ ". And I'm " + str(age
) + " years old.")
print("Hi, I'm %s. I'm from %s. And I'm %d years old." %(name
, country
, age
))
print("Hi, I'm {}. I'm from {}. And I'm {} years old.".format(name
, country
, age
))
print(f
"Hi, I'm {name}. I'm from {country}. And I'm {age} years old.")
Hi, I'm Jack. I'm from China. And I'm 18 years old.
Hi, I'm Jack. I'm from China. And I'm 18 years old.
Hi, I'm Jack. I'm from China. And I'm 18 years old.
Hi, I'm Jack. I'm from China. And I'm 18 years old.
3. Yield 语法
def fibo(n
):
a
= 0
b
= 1
nums
= []
for _
in range(n
):
nums
.append
(a
)
a
, b
= b
, a
+b
return nums
for i
in fibo
(6):
print(i
)
0
1
1
2
3
5
def fibo_y(n
):
a
= 0
b
= 1
for _
in range(n
):
yield a
a
, b
= b
, a
+b
for i
in fibo_y
(6):
print(i
)
0
1
1
2
3
5
4. 列表解析式
fruit
= ['apple', 'pear', 'pineapple', 'orange', 'banana']
for i
in range(len(fruit
)):
fruit
[i
] = fruit
[i
].upper
()
fruit
['APPLE', 'PEAR', 'PINEAPPLE', 'ORANGE', 'BANANA']
fruits
= ['apple', 'pear', 'pineapple', 'orange', 'banana']
fruits
= [x
.upper
() for x
in fruits
]
fruits
['APPLE', 'PEAR', 'PINEAPPLE', 'ORANGE', 'BANANA']
fruits
= ['apple', 'pear', 'pineapple', 'orange', 'banana']
filtered_fruits
= [x
for x
in fruits
if x
.startswith
('p')]
filtered_fruits
['pear', 'pineapple']
5. Enumerate函数
fruits
= ['apple', 'pear', 'pineapple', 'orange', 'banana']
for i
, x
in enumerate(fruits
):
print(i
, x
)
0 apple
1 pear
2 pineapple
3 orange
4 banana
6.1 反向遍历
fruits
= ['apple', 'pear', 'pineapple', 'orange', 'banana']
for i
, x
in enumerate(reversed(fruits
)):
print(i
, x
)
0 banana
1 orange
2 pineapple
3 pear
4 apple
6.2 按顺序遍历
fruits
= ['apple', 'pear', 'pineapple', 'orange', 'banana']
for i
, x
in enumerate(sorted(fruits
)):
print(i
, x
)
0 apple
1 banana
2 orange
3 pear
4 pineapple
7. 字典的合并操作
a
= {'ross': '12', 'xiaoming': '23'}
b
= {'lilei': '34', 'zhangsan': '45'}
c
= {**a
, **b
}
c
{'ross': '12', 'xiaoming': '23', 'lilei': '34', 'zhangsan': '45'}
8. 三元运算符
score
= [56, 63, 80, 20, 100]
s
= ['pass' if x
>60 else 'fail' for x
in score
]
s
['fail', 'pass', 'pass', 'fail', 'pass']
9. 序列解包
name
= 'Jack Tim'
first_name
, last_name
= name
.split
()
first_name
, last_name
('Jack', 'Tim')
10. with语句
f
= open('haha.txt', 'r')
s
= f
.read
()
f
.close
()
with open('haha.txt', 'r') as f
:
s
= f
.read
()
参考内容
https://www.bilibili.com/video/BV1kT4y1u72i?from=search&seid=12924391744156658505