Python 小技巧 —— 元组 | 格塔里

格塔里

一个不负责任的教程博客

0%

Python 小技巧 —— 元组

定量接收

1
2
3
4
5
6
7
8
9
>>> a, b = (1, 2)
>>> print('a is: %s, b is: %s'%(a, b))
a is: 1, b is: 2
>>> a, b = (1, [2, 3])
>>> print('a is: %s, b is: %s, b[0] is: %s, b[1] is: %s'%(a, b, b[0], b[1]))
a is: 1, b is: [2, 3], b[0] is: 2, b[1] is: 3
>>> a, [b, c] = (1, [2, 3])
>>> print('a is: %s, b is: %s, c is: %s'%(a, b, c))
a is: 1, b is: 2, c is: 3

不定量接收

1
2
3
>>> *a, b = (1, 2, 3, 4, 5, 6)
>>> print('a is: %s, b is: %s'%(a, b))
a is: [1, 2, 3, 4, 5], b is: 6

占位符拆分

1
2
3
4
5
6
>>> *a, _, b = (1, 2, 3, 4, 5, 6)
>>> print('a is: %s, b is: %s, _ is: %s'%(a, b, _))
a is: [1, 2, 3, 4], b is: 6, _ is: 5
>>> *a, _, b, _ = (1, 2, [3, 4], 5, 6)
>>> print('a is: %s, b is: %s, _ is: %s'%(a, b, _))
a is: [1, 2, 3], b is: 5, _ is: 6

写在最后

PHP 是世界上最好的编程语言!