# list slice用法 - 通過在Python中切片列表來分配值的緊湊方式

## reverse 2d (5)

``bar = ['a','b','c','x','y','z']``

``v1, v2, v3 = [bar[0], bar[3], bar[4]]``

``my(\$v1, \$v2, \$v3) = @bar[0,3,4];``

``````indices = (0,3,4)
v1, v2, v3 = [bar[i] for i in indices]

>>> print v1,v2,v3     #or print(v1,v2,v3) for python 3.x
a x y``````

`numpy` ，您可以使用包含索引的另一個數組索引數組。 這允許非常緊湊的語法，完全按照您的要求：

``````In [1]: import numpy as np
In [2]: bar = np.array(['a','b','c','x','y','z'])
In [3]: v1, v2, v3 = bar[[0, 3, 4]]
In [4]: print v1, v2, v3
a x y``````

``````from itertools import compress

bar = ['a','b','c','x','y','z']
v1, v2, v3 = compress(bar, (1, 0, 0, 1, 1, 0))``````

``v1, v2, v3 = compress(bar, (1, 0, 0, 1, 1,))``

``````bar = ['a','b','c','x','y','z']
v1, _, _, v2, v3, _ = bar``````

While I don't have a complex comparison as most of these answers do, I would like to share my method for handling this situation. By extending `IEnumerable<T>` , you can allow your `Team` class to support Linq query extensions, without publicly exposing all the methods and properties of `List<T>` .

``````class Team : IEnumerable<Player>
{
private readonly List<Player> playerList;

public Team()
{
playerList = new List<Player>();
}

public Enumerator GetEnumerator()
{
return playerList.GetEnumerator();
}

...
}

class Player
{
...
}
``````