紧凑的方式来通过在Python中切分列表来分配值

我有以下列表

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]; 

你可以使用operator.itemgetter

 >>> from operator import itemgetter >>> bar = ['a','b','c','x','y','z'] >>> itemgetter(0, 3, 4)(bar) ('a', 'x', 'y') 

所以对于你的例子,你会做到以下几点:

 >>> v1, v2, v3 = itemgetter(0, 3, 4)(bar) 

假设你的指数既不dynamic也不太大,我会一起去的

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

既然你想要紧凑,你可以这样做:

 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 axy 

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 axy 

对于你的简单情况,使用numpy最可能是矫枉过正的。 我只是提到它的完整性,以防你需要做大量的数据。

又一种方法:

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

另外,您可以忽略列表的长度,并在select器的末尾跳过零:

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

https://docs.python.org/2/library/itertools.html#itertools.compress