Compact way to assign values by slicing list in Python

后端 未结 5 1200
悲哀的现实
悲哀的现实 2020-12-01 07:04

I have the following list

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

What I want to do is to assign 1st, 4th and 5th values of bar

相关标签:
5条回答
  • 2020-12-01 07:45

    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)
    
    0 讨论(0)
  • 2020-12-01 08:03

    In numpy, you can index an array with another array that contains indices. This allows for very compact syntax, exactly as 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
    a x y
    

    Using numpy is most probably overkill for your simple case. I just mention it for completeness, in case you need to do the same with large amounts of data.

    0 讨论(0)
  • 2020-12-01 08:05

    Since you want compactness, you can do it 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
    a x y
    
    0 讨论(0)
  • 2020-12-01 08:10

    Assuming that your indices are neither dynamic nor too large, I'd go with

    bar = ['a','b','c','x','y','z']
    v1, _, _, v2, v3, _ = bar
    
    0 讨论(0)
  • 2020-12-01 08:10

    Yet another method:

    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 length of the list and skip zeros at the end of selectors:

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

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

    0 讨论(0)
提交回复
热议问题