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




reverse 2d (5)

我有以下清單

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

我想要做的是將第1,第4和第5個值分配給v1,v2,v3 ,是否有比這更簡潔的方法:

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

因為在Perl中你可以這樣做:

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

Answers

既然你想要緊湊,你可以做如下的事情:

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

對於你的簡單案例,使用numpy很可能是矯枉過正。 我只是提到它的完整性,以防你需要對大量數據做同樣的事情。



假設你的指數既不動態也不太大,我會選擇

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
{
    ...
}




python list slice