Python3 - 常用编程技巧

Python3 - 常用编程技巧

掌握 Python 常用技巧,可大量节省开发和精力。包括数组分解、变量置换,字符串、集合、函数参数、系统相关功能等

1. 列表分解

通过列表分解,可以将列表中的值逐一赋值给变量。

1
2
3
first_name, last_name = ['Farhad', 'Malik']
print(first_name) # Farhad
print(last_name) # Malik

运行输出

1
2
Farhad
Malik

2. 交换变量值

python 中的交换变量非常简单,一行 A,B=B,A 即可

1
2
3
4
first_name, last_name = ['Farhad', 'Malik']
last_name, first_name = first_name, last_name
print(first_name) #It will print Malik
print(last_name) #It will print Farhad

运行输出

1
2
Malik
Farhad

3. 重复字符串

1
2
>>> 'A'*3
>>> AAA

4. 字符串反转

1
2
3
x = 'abc'
x = x[::-1]
print(x)

输出

1
cba

5. 负数索引

如果要从最后一个字符开始,请使用负索引。

1
2
y = '1234'
print(y[-1])

输出

1
4

6. 集合交集

1
2
3
4
a = {1,2,3,5}
b = {3,4,5,8}
c = a.intersection(b)
print(c)

输出

1
{3,5}

7. 集合差集

1
2
3
4
a = {1,2,3,5}
b = {3,4,5,8}
c = a.difference(b)
print(c)

输出

1
{1, 2}

8. 集合并集

1
2
3
4
a = {1,2,3,5}
b = {3,4,5,8}
c = a.union(b)
print(c)

输出

1
{1, 2, 3, 4, 5, 8}

9. 参数默认值

我们可以通过为参数提供默认值来传递可选参数:

1
2
3
4
def my_new_function(my_value='hello'):
  print(my_value)#Calling
my_new_function() # 打印 hello
my_new_function('test') # 打印 test

输出

1
2
hello
test

10. 使用*arguments 的未知参数

============================================

如果您的函数可以接受任意数量的参数,则在参数名称前添加一个*:

1
2
3
4
5
6
7
8
9
10
a='a'
b='b'
c='c'
def myfunc(*arguments):
  print('args:')
  for a in arguments:
    print (a)
myfunc(a)
myfunc(a,b)
myfunc(a,b,c)

输出

1
2
3
4
5
6
7
8
9
args:
a
args:
a
b
args:
a
b
c

11. 使用**arguments 作为参数的字典

====================================================

它允许您将不同数量的关键字参数传递给函数。

您还可以将字典值作为关键字参数传递:

1
2
3
4
def myfunc1(**arguments):
  return arguments.keys(), arguments.values()

print(myfunc1(a=1,b=2))

输出

1
(dict_keys(['a', 'b']), dict_values([1, 2]))

12. 返回多个值

一个函数可以返回多个值:

1
2
3
4
def get_result():
    return 'hello',2
resultA, resultB = get_result()
print(resultA, resultB)

输出

1
hello 2

13. 释放内存

1
2
import gc
collected_objects = gc.collect()

14. 数组合并成字符串

1
2
name = ["FinTech", "Explained"]
print(" ".join(name))

输出

1
FinTech Explained

15. 对象的内存占用量

1
2
3
import sys
x = 'farhadmalik'
print(sys.getsizeof(x))

输出

1
60

16. 打印当前目录

1
2
import os
print(os.getcwd())
  1. 打印导入的模块
1
2
import sys
imported_modules = [m.__name__ for m in sys.modules.values() if m]
  1. 获取当前进程的 ID
1
2
3
import os

os.getpid()

以上在 python3.7 测试通过。

Rating: