Escritura específica de Python
2020-10
- Intercambio variable
temp = a
a = b
b = a
# Python特有
a, b = b, a
- Comprensión de listas
my_list = []
for i in range(10):
my_list.append(i * 2)
# 推导式
my_list = [i * 2 for i in range(10)]
- Recorrido con índice
for i in range(len(my_list)):
print(i, "-->", my_list[i])
for i, item in enumerate(my_list):
print(i, "-->", item)
- Desembalaje de secuencia
a, *rest = [1, 2, 3]
a, *middle, c = [1, 2, 3, 4]
- Empalme de cuerdas
letters = ['s', 'p', 'a', 'm']
s = ""
for let in letters:
s += let
# 用join
letters = ['s', 'o', 'a']
word = ''.join(letters)
- Juicio verdadero y falso
De hecho, ""
, []
, {}
estos contenedores sin ningún elemento es falsa, se pueden utilizar directamente if not xx
para determinar.
if attr:
print("true")
if not attr:
print("not true")
- Acceder a los elementos del diccionario
d = {
'hello': 'world'}
# 有值的话
if d.has_key('hello'):
print(d['hello']) # prints 'world'
else:
print('default_value')
# 推荐使用get, 有异常错误处理
d = {
'hello': 'world'}
print(d.get('hello', 'default_value')) # prints 'world'
print(d.get('thingy', 'default_value')) # prints 'default_value'
- Lista de operaciones
a_list = [3, 4, 5]
b_list = []
for item in a_list:
if item > 4:
b_list.append(item)
a_list = [3, 4, 5]
b_list = [i for i in a_list if i > 4]
# or
b_list = filter(lambda x : x > 4, a)
a_list = [3, 4, 5]
b_list = map(lambda i : i + 3, a)
# b_list = [6, 7, 8]
- Usar marcador de posición
Algunos no necesitan, pero tienen que aceptar
file_name = 'foot.txt'
base_name, _, ext = file_name.rpartition('.')