Python编程小技巧

变量值交换

引入第三变量进行值的交换

>>> a = 12
>>> b = 7
>>> sum = a
>>> a = b
>>> b = sum
>>> print(a, b)
7 12

不需要第三变量进行值的交换

>>> a = 12
>>> b = 7
>>> a = a + b
>>> b = a - b
>>> a = a - b
>>> print(a, b)
7 12

Python中非常简单易用的变量值交换方法

>>> a = 12
>>> b = 7
>>> print(a, b)
12 7
>>> a, b = b, a
>>> print(a, b)
7 12

取列表的头和尾

>>> x = [12, 32, 24, 33, 21, 64, 11, 25]
>>> a, *b, c = x
>>> print(a, c)
12 25
>>> print(b)
[32, 24, 33, 21, 64, 11]
>>> a, b, c, *_, d = x
>>> print(a, b, c, d)
12 32 24 25
>>> print(_)
[33, 21, 64, 11]

其中 * 代表所有,各个变量一一对应皆可从列表中取出值来。

你可能感兴趣的:(Python编程小技巧)