A compact way to assign values ​​to a list of sections in Python

I have the following list

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

What I want to do is assign 1, 4 and 5 to the bar values ​​in v1,v2,v3 , there is a more compact way to do this:

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

Because in Perl, you can do something like this:

 my($v1, $v2, $v3) = @bar[0,3,4]; 
+45
python list slice
Mar 31 '14 at 8:15
source share
5 answers

You can use operator.itemgetter :

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

So, for your example, you would do the following:

 >>> v1, v2, v3 = itemgetter(0, 3, 4)(bar) 
+87
Mar 31 '14 at 8:16
source share

Assuming your indexes are neither dynamic nor too large, I would go with

 bar = ['a','b','c','x','y','z'] v1, _, _, v2, v3, _ = bar 
+44
Mar 31 '14 at 12:46
source share

Since you want compactness, you can do something as follows:

 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 
+35
Mar 31 '14 at 8:18
source share

In numpy you can index an array with another array that contains indexes. This allows you to use a very compact syntax exactly the way you want:

 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 

Using numpy is likely to be redundant for your simple case. I just mentioned this for completeness if you need to do the same with large amounts of data.

+21
Mar 31 '14 at 8:20
source share

Another way:

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

In addition, you can ignore the length of the list and skip zeros at the end of the selectors:

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

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

+7
Mar 31 '14 at 12:59
source share



All Articles