Python-specific writing
2020-10
- Variable exchange
temp = a
a = b
b = a
# Python特有
a, b = b, a
- List comprehension
my_list = []
for i in range(10):
my_list.append(i * 2)
# 推导式
my_list = [i * 2 for i in range(10)]
- Traversal with index
for i in range(len(my_list)):
print(i, "-->", my_list[i])
for i, item in enumerate(my_list):
print(i, "-->", item)
- Sequence unpacking
a, *rest = [1, 2, 3]
a, *middle, c = [1, 2, 3, 4]
- String splicing
letters = ['s', 'p', 'a', 'm']
s = ""
for let in letters:
s += let
# 用join
letters = ['s', 'o', 'a']
word = ''.join(letters)
- True and false judgment
Indeed, ""
, []
, {}
these containers without any element is false, can be used directly if not xx
to determine.
if attr:
print("true")
if not attr:
print("not true")
- Access dictionary elements
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'
- Operation list
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]
- Use placeholder
Some do not need, but have to accept
file_name = 'foot.txt'
base_name, _, ext = file_name.rpartition('.')